Skip to main content

Python Bitwise Operators

Bitwise Operators

Bitwise operators act on bits and perform the bit-by-bit operations.

These are used to operate on binary numbers.

OperatorDescriptionExample
&Bitwise ANDx & y = 0 (0000 0000)
&124;Bitwise ORx &124; y = 14 (0000 1110)
~Bitwise NOT~x = -11 (1111 0101)
^Bitwise XORx ^ y = 14 (0000 1110)
>>Bitwise right shiftx >> 2 = 2 (0000 0010)
<<Bitwise left shiftx << 2 = 40 (0010 1000)

Examples

Bitwise AND, OR, NOT, XOR

a = 10
b = 2

print(a & b) # 2
print(a | b) # 10
print(~a) # -11
print(a ^ b) # 8

Bitwise right shift and left shift

a = 10
b = -10

# print bitwise right shift operator
print(a >> 1) # 5
print(b >> 1) # -5

a = 5
b = -10

# print bitwise left shift operator
print(a << 1) # 10
print(b << 1) # -20

Table of Contents