Python Bitwise Operators

July 12, 2022

Use the code below written in Python to display the binary numbers of 6 and 4. The binary numbers will be used as a reference point going forward.

print(bin(6))
# 0b110

print(bin(4))
# 0b100

AND (&)

Using the & operator to compare each digit in the binary numbers. If both numbers have 1’s in the same place, the digit remains a 1, otherwise it becomes 0.

print(bin(6&4))
# 0b100

OR (|)

Using the | operator to compare each digit in the binary numbers. If either numbers have 1’s in the same place, the digit remains a 1, otherwise it becomes 0.

print(bin(6|4))
# 0b110

Right Shift (>>)

Using the >> operator to shift the binary digits to the right, the number of times after the >> symbol. Below the binary digits for 6 will shift to the right 1 digit.

print(bin(6>>1))
# 0b11

Left Shift (<<)

Using the << operator to shift the binary digits to the left, the number of times after the << symbol. Below the binary digits for 6 will shift to the left 1 digit.

print(bin(6<<1))
# 0b1100

NOT (~)

Using the ~ operator returns the compliment of the number. An easy way to calculate the compliment of a number is to take the negative of that number and subtract 1, i.e., -(x) - 1.

print(~0)
# -1
print(~-1)
# 0
print(~-2)
# 1
print(~-3)
# 2

XOR (^)

Using the ^ operator to compare each digit in the binary numbers. If both numbers have 1’s or 0’s in the same place, the digit becomes 0. If only one number has a 1 in that place, then it becomes 1.

print(bin(6^4))
# 0b10

Profile picture


Database Analyst at NYFB | M.S. in Data Science student at New Jersey Institute of Technology.

Copyright © 2023 travisvirgil