Bitwise Operators
Bitwise Operators are used to perform bit level operations. The following table lists out all the bitwise operators in Python.
Operator Symbol | Description | Example |
---|---|---|
& | AND | x & y |
| | OR | x | y |
^ | XOR | x ^ y |
~ | NOT | ~x |
<< | Zero fill left shift | x << y |
>> | Signed right shift | x >> y |
AND Bitwise Operator
AND Bitwise Operator performs AND gate operation on the input bits. The following table provides the output for possible input bit combinations.
x | y | x & y |
---|---|---|
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
All the input gates must be ON for the output to be ON.
OR Bitwise Operator
OR Bitwise Operator performs OR gate operation on the input bits. The following table provides the output for possible input bit combinations.
x | y | x | y |
---|---|---|
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
At least one of the input gates must be ON for the output to be ON.
XOR Bitwise Operator
XOR Bitwise Operator performs XOR gate operation on the input bits. The following table provides the output for possible input bit combinations.
x | y | x ^ y |
---|---|---|
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
Only one of the two input gates must be ON for the output to be ON.
NOT Bitwise Operator
XOR Bitwise Operator performs XOR gate operation on the input bits. The following table provides the output for possible input bit combinations.
x | ~ x |
---|---|
1 | 0 |
0 | 1 |
The input state is inverted in the output. If the input gate is ON, the output is OFF, and if the input gate is OFF, then the output gate is ON.
Zero Fill Left Shift Bitwise Operator
Zero fill left shift operator <<
, with x and y as left and right operands x << y
, shifts the bits of x
by y
number of positions to the left side. For each shift to the left, a zero is added on the left side, and the bits on the right are overflown.
Signed Right Shift Bitwise Operator
Signed right shift operator >>
, with x and y as left and right operands x >> y
, shifts the bits of x
by y
number of positions to the right side. The right most sign bit remains unchanged. The bits shifted to the left and out are overflown. During the shift, a zero is filled on the right side of x
, excluding the sign bit.
Example
In the following program, we take integer values for x
and y
, and perform bitwise operations with x and/or y as operands.
Python Program
# AND
x, y = 5, 2
print(x & y) # output is 0
# OR
x, y = 5, 2
print(x | y) # output is 7
# XOR
x, y = 5, 2
print(x ^ y) # output is 7
# NOT
x, y = 5, 2
print(~x) # output is -6
# Zero fill left shift
x, y = 5, 2
print(x << y) # output is 20
#Signed right shift
x, y = 5, 2
print(x >> y) # output is 1
Conclusion
In this Python Tutorial, we learned about all the Bitwise Operators in Python, their input-output tables, and their working with examples.