Bitwise Operators in Python

Bitwise Operators allow you to perform operations on binary numbers.

The values are automatically converted to binary and then the logic is applied to them.

The output is also converted back from binary implicitly.

They are:

  • &: AND

Only the first bit is 1 in 1010 and 1000, so the operator returns, as a result, the first as 1 and the rest as 0.

10 # 1010
8 # 1000
print(10 & 8)
8 # 1000
  • |: OR

Since 1010 has 1\’s in the first and third position and 1000 in the first position only, the operator returns 1010 because it only needs 1 in one of the binary positions to return 1.

10 # 1010
8 # 1000
print(10 | 8)
10 # 1010
  • ~: NOT

Returns the complement, just switch each 1 for a 0 and vice versa. The extra 1\’s zeros to the left that were not shown by default.

10 # 1010
print(~10)
11 # 1111111111110101
  • ^: XOR

The XOR operator returns 1 only when there is a 1 and a 0, it returns 0 when both bits are 0 or both are 1.

In this example only the third bit returns 1.

10 # 1010
8 # 1000
print(10 ^ 8)
2 # 0010
  • >>: Right Shift

This example takes 1010 and shifts to the right by 1 place.

You can see the 101 from the beginning of 1010 moving to the end resulting in 0101 which is 5 in decimal.

10 # 1010
print(10 >> 1)
5 # 0101
  • <<: Left Shift

This example takes 1010 and shifts to the left by 1 place.

The operator puts another zero at the end to perform this shift resulting in 10100 which is 20 in decimal.

10 # 1010
print(10 << 1)
20 # 10100