Bitwise Operators
In Python, bitwise operators are used to performing bitwise operations on integers. To perform bitwise, we first need to convert integer value to binary (0 and 1) value. The bitwise operator operates on values bit by bit, so it is called bitwise. It always returns the result in integer format. Python has 6 bitwise operators as listed below.
&Bitwise and|Bitwise or^Bitwise xor~Bitwise 1's complement<<Bitwise left-shift>>Bitwise right-shift
| Operator | Name | Example | Result | Binary Operation |
|---|---|---|---|---|
& |
AND | 5 & 3 |
1 |
0101 & 0011 = 0001 |
| |
OR | 5 | 3 |
7 |
0101 | 0011 = 0111 |
^ |
XOR | 5 ^ 3 |
6 |
0101 ^ 0011 = 0110 |
~ |
NOT | ~5 |
-6 |
Flips all bits |
<< |
Left Shift | 5 << 1 |
10 |
0101 → 1010 |
>> |
Right Shift | 5 >> 1 |
2 |
0101 → 0010 |
Example:
a = 5 # binary: 0101
b = 3 # binary: 0011
print(a & b) # 1 — AND
print(a | b) # 7 — OR
print(a ^ b) # 6 — XOR
print(~a) # -6 — NOT
print(a << 1) # 10 — Left Shift
print(a >> 1) # 2 — Right Shift
Output:
1
7
6
-6
10
2