Python: Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation.

OperatorsDescriptionSyntax
Bitwise AND(&)Operator copies a bit to the result if it exists in both operands.a&b
Bitwise OR(|)It copies a bit if it exists in either operand.a|b
Bitwise XOR(^)It copies the bit if it is set in one operand but not both.a^b
Bitwise NOT(~)It inverts all the bits.~a
Bitwise Right Shift(>>)It shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.a>>
Bitwise Left Shift(<<)It shifts left by pushing zeros in from the right and let the leftmost bits fall off.a<<

Example: 

a = 20
b = 2

print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output:

0
22
-21
22
5
80
Tags