Bitwise Operators in Python

What are Bitwise Operators?

Bitwise operators operate on the binary representations of integers. They perform bit-level operations and are very useful in system programming, embedded programming, and performance-optimized code.

Bitwise Operators Table

Operator Name Description Example
& AND Sets each bit to 1 if both bits are 1 5 & 3 = 1
| OR Sets each bit to 1 if one of two bits is 1 5 | 3 = 7
^ XOR Sets each bit to 1 if only one of two bits is 1 5 ^ 3 = 6
~ NOT Inverts all the bits ~5 = -6
<< Left Shift Shifts bits to the left by a specified number of positions 5 << 1 = 10
>> Right Shift Shifts bits to the right by a specified number of positions 5 >> 1 = 2

Examples

a = 5       # 0b0101
b = 3       # 0b0011

print(a & b)   # 1 (0b0001)
print(a | b)   # 7 (0b0111)
print(a ^ b)   # 6 (0b0110)
print(~a)      # -6 (inverts all bits)
print(a << 1)  # 10 (0b1010)
print(a >> 1)  # 2 (0b0010)

Tip

Use bin() to see the binary form of a number in Python:

print(bin(5))  # Output: '0b101'