Python Bitwise Operators
Bitwise operators work directly on the binary representations of integers. They operate bit by bit (each binary digit) and are commonly used in low-level programming, performance optimization, and tasks involving flags or masks.
Common Bitwise Operators in Python
| Operator | 
Name | 
Description | 
Example | 
& | 
AND | 
Sets each bit to 1 if both bits are 1 | 
a & b | 
| ` | 
` | 
OR | 
Sets each bit to 1 if one of two bits is 1 | 
^ | 
XOR (Exclusive OR) | 
Sets each bit to 1 if only one of the bits is 1 | 
a ^ b | 
~ | 
NOT (Bitwise Complement) | 
Inverts all the bits | 
~a | 
<< | 
Left Shift | 
Shifts bits to the left, filling with zeros | 
a << 2 | 
>> | 
Right Shift | 
Shifts bits to the right, discarding bits on the right | 
a >> 2 | 
Explanation and Examples
Let's take two numbers for examples:
a = 60  # In binary: 0011 1100
b = 13  # In binary: 0000 1101
1. Bitwise AND (&)
Sets each bit to 1 only if both bits are 1.
result = a & b
# 0011 1100
# 0000 1101
# --------
# 0000 1100  => 12 in decimal
print(result)  # Output: 12
2. Bitwise OR (|)
Sets each bit to 1 if either bit is 1.
result = a | b
# 0011 1100
# 0000 1101
# --------
# 0011 1101  => 61 in decimal
print(result)  # Output: 61
3. Bitwise XOR (^)
Sets each bit to 1 if only one of the bits is 1 (but not both).
result = a ^ b
# 0011 1100
# 0000 1101
# --------
# 0011 0001  => 49 in decimal
print(result)  # Output: 49
4. Bitwise NOT (~)
Inverts all bits (flips 0s to 1s and 1s to 0s).
Note: Python uses two’s complement for negative numbers.
result = ~a
# a = 60 (0011 1100)
# ~a = 1100 0011 (in two's complement, represents -61)
print(result)  # Output: -61
5. Left Shift (<<)
Shifts bits to the left by the specified number of positions, filling with zeros on the right.
result = a << 2
# 0011 1100 << 2 -> 1111 0000
# decimal 240
print(result)  # Output: 240
6. Right Shift (>>)
Shifts bits to the right by the specified number of positions, discarding bits on the right.
result = a >> 2
# 0011 1100 >> 2 -> 0000 1111
# decimal 15
print(result)  # Output: 15
Summary Table with Output
a = 60  # 0011 1100
b = 13  # 0000 1101
print("a & b =", a & b)   # 12
print("a | b =", a | b)   # 61
print("a ^ b =", a ^ b)   # 49
print("~a =", ~a)         # -61
print("a << 2 =", a << 2) # 240
print("a >> 2 =", a >> 2) # 15