Bitwise Operators
Python · Operators
Theory
Bitwise operators work on the binary digits (bits) of integers. With a = 5 (binary 101) and b = 3 (binary 011): & keeps bits set in both (001 = 1), | keeps bits set in either (111 = 7), ^ keeps bits set in exactly one (110 = 6), << shifts bits left (5 << 1 is 1010 = 10, the same as multiplying by 2), and >> shifts right (5 >> 1 is 2, like floor dividing by 2). bin(5) shows '0b101'.
~ inverts all bits; because Python integers behave like two's complement with infinite sign bits, ~x always equals -x - 1, so ~5 is -6. Do not confuse & and | with and and or: the bitwise versions work bit by bit and do not short-circuit. In data work you meet them most in pandas, where & and | combine boolean columns, e.g. (df.age > 18) & (df.city == 'Pune'), and each condition needs its own parentheses because & binds tighter than >.
Why we use it
Bits are a compact way to store many yes/no flags in one integer, such as permission masks, and shifts are fast multiply/divide by powers of two. In pandas, & and | are the only way to combine filter conditions.
When to use it
Reach for bitwise operators for flags, masks, low-level protocols and pandas boolean filters. For ordinary if conditions on Python values, use and, or and not instead, which are clearer and short-circuit.
How it works
- Evaluate 5 & 3
- Write both numbers in binary: 101 and 011
- Compare bit by bit at each position
- Is the bit 1 in both numbers? Yes: Result bit is 1. No: Result bit is 0.
- Convert the result bits back to decimal: 001
- Output: 1
Syntax
& | ^ ~ << >>Example
print(5 & 3) # 1
print(5 | 3) # 7
print(5 << 1) # 10Key points
- & is AND, | is OR, ^ is XOR, ~ is NOT, << and >> shift bits
- ~x always equals -x - 1, so ~5 is -6
- x << 1 doubles x; x >> 1 floor-halves it
- In pandas, combine conditions with & and | and wrap each in parentheses
- Common in low-level programming, flags, and permission masks