Bitwise Operators in Python
Bitwise operators work directly on the binary representation of integers, one bit at a time. They come up less often than arithmetic or logical operators, but show up in flags, permission systems, and performance-sensitive code. Python supports & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).
& compares bit by bit
Keeps a 1 only where both numbers have a 1 in that position.
| compares bit by bit
Keeps a 1 where either number has a 1 in that position.
^ (XOR) compares bit by bit
Keeps a 1 only where the two bits differ.
<< shifts bits left
Each position shifted doubles the number.
>> shifts bits right
Each position shifted halves the number, rounding down.
print(6 & 3)print(6 | 3)print(6 ^ 3)print(1 << 4)print(16 >> 2)Using Bits as Flags
A common pattern for compactly storing several on/off settings in one number, combining them with | and checking them with &.
READ = 1WRITE = 2permissions = READ | WRITEprint(permissions)Fast Multiply by a Power of 2
Shifting bits left is a quick way to multiply by 2, though everyday Python code usually favors * for readability unless performance is critical.
doubled = 5 << 1print(doubled)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.