Operators in Python
8. Bitwise Operators
- Bitwise operators are used to manage individual bits with integers. These operators works on binary representation of integers and performs bit-level operations. Python supports several bitwise operators : AND, OR, XOR, NOT, left shift and right shift.
- Bitwise operators work on bits and perform bit by bit operation. In binary operations, numbers are treated as string of bits. For example, 0 is represented by 0, 1 is represented by 1, and 2 is represented by 10 in binary.
|
Sl No. |
Operators |
Functions |
|
1 |
x << y |
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y |
|
2 |
x >> y |
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y |
|
3 |
x & y |
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0 |
|
4 |
y |
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1 |
|
5 |
~ x |
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1 |
|
6 |
x ^ y |
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1 |