Introduction to Python Bitwise Operators
Python Bitwise Operators are used to perform bit by bit operations. It will convert the number into the binary form and then perform the specified operation. These operators do not return True or False, instead perform bitwise calculations.
Operator | Name | Description |
---|---|---|
& | Bitwise AND | Returns binary 1 if both bits are 1, else 0. |
| | Bitwise OR | Returns binary 1 if any of the bit is 1, else 0. |
^ | Bitwise XOR | Return binary 1 if only 1 bit is 1. |
~ | Bitwise NOT | Convert’s 1s to 0s and 0s to 1s. |
<< | Bitwise left shift | Shifts bits left and fills new bits with 0. |
>> | Bitwise right shift | Shifts bits right and fills new bits with 0. |
Python Bitwise Operators
Bitwise AND Operator
It returns binary 1 if all the bits are 1, and if any of the bits is 0, then it returns 0.
Illustration:
Numeric Value | Binary Value | |
---|---|---|
2 | 010 | |
3 | 011 | |
Bitwise AND | 2 | 010 |
Example:
print(2 & 3)
Bitwise OR Operator
It returns binary 1 if any of the bits is 1, and if all the bits are 0, then it returns 0.
Illustration:
Numeric Value | Binary Value | |
---|---|---|
2 | 010 | |
3 | 011 | |
Bitwise OR | 3 | 011 |
Example:
print(2 | 3)
Bitwise XOR Operator
It returns 1 only if one of the bits is 1, i.e. one bit is 1 and the second is 0. It returns 0 if both the bits are same, either 1 or 0.
The Caret sign (^) is used for Bitwise XOR.
Illustration:
Numeric Value | Binary Value | |
---|---|---|
2 | 010 | |
3 | 011 | |
Bitwise XOR | 1 | 001 |
Example:
print(2 ^ 3)
Bitwise NOT Operator
It inverts the bits of the number, i.e. replaces 1’s with 0’s and 0’s with 1’s.
Bitwise or operator inverts the number as per the 2’s compliment. Bitwise NOT of number x results in -(x + 1).
The Tilde sign (~) is used for Bitwise NOT.
Illustration:
Numeric Value | Bitwise NOT |
---|---|
3 | -4 |
-4 | 3 |
Example:
print(~3)
print(~-4)
Bitwise left shift Operator
It moves the bits left by the specified number of positions.
Illustration:
Numeric Input | Bitwise Value | Left shift by 1 | Numeric Output |
---|---|---|---|
2 | 0010 | 0100 | 4 |
4 | 0100 | 1000 | 8 |
Example:
print(2 << 1)
print(4 << 1)
Bitwise right shift Operator
It moves the bits right by the specified number of positions.
Illustration:
Numeric Input | Binary Value | Right shift by 1 | Numeric Output |
---|---|---|---|
2 | 0010 | 0001 | 1 |
4 | 0100 | 0010 | 2 |
Example:
print(2 >> 1)
print(4 >> 1)