Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations.
These are used to operate on binary numbers.
| Operator | Description | Example |
|---|---|---|
& |
Bitwise AND | x & y = 0 (0000 0000) |
&124; |
Bitwise OR | x &124; y = 14 (0000 1110) |
~ |
Bitwise NOT | ~x = -11 (1111 0101) |
^ |
Bitwise XOR | x ^ y = 14 (0000 1110) |
>> |
Bitwise right shift | x >> 2 = 2 (0000 0010) |
<< |
Bitwise left shift | x << 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) # 8Bitwise 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