Python integers may be manipulated bitwise and the standard bit operations are supported: inversion, bitwise AND, OR, and exclusive OR (a.k.a. XOR), and left and right shifting. Here are some facts regarding the bit operators:
Negative numbers are treated as their 2’s complement value.
Left and right shifts of N bits are equivalent to multiplication and division by (2 ** N) without overflow checking.
For long integers, the bit operators use a “modified” form of 2’s complement, acting as if the sign bit were extended infinitely to the left.
The bit inversion operator ( ~ ) has the same precedence as the arithmetic unary operators, the highest of all bit operators. The bit shift operators ( << and >> ) come next, having a precedence one level below that of the standard plus and minus operators, and finally we have the bitwise AND, XOR, and OR operators (&, ^, | ), respectively. All of the bitwise operators are presented in the order of descending priority in following Table.
Integer Type Bitwise Operators
|~ num||(unary) invert the bits of num, yielding -( num + 1)|
|num1 << num2||expr1 left shifted by expr2 bits|
|num1 >> num2||expr1 right shifted by expr2 bits|
|num1 & num2||expr1 bitwise AND with expr2|
|num1 ^ num2||expr1 bitwise XOR (exclusive OR) with expr2|
|num1 | num2||expr1 bitwise OR with expr2|
We will now present some examples using the bit operators using 30 (011110), 45 (101101), and 60 (111100):
>>> 30 & 45 12 >>> 30 | 45 63 >>> 45 & 60 44 >>> 45 | 60 61 >>> ~30 -31 >>> ~45 -46 >>> 45 << 1 90 >>> 60 >> 2 15 >>> 30 ^ 45 51