Bitwise Operations
Bitwise operations apply logic gates to each bit of an integer independently and in parallel.
The core operators
AND, OR, XOR, and NOT act on corresponding bits of their operands. AND yields 1 only where both bits are 1; OR where at least one is; XOR where exactly one is; NOT flips every bit.
Truth of XOR
XOR is especially useful: it is its own inverse, so applying the same value twice restores the original. This underlies simple swaps, parity, and stream cipher constructions.
Bit tricks
- Test a bit: (x >> i) & 1
- Set a bit: x | (1 << i)
- Clear a bit: x & ~(1 << i)
- Toggle a bit: x ^ (1 << i)
- Check power of two: x & (x - 1) == 0
Why they are fast
Each bitwise operation processes all bits of a word at once in a single machine instruction. This parallelism makes them the building blocks of masks, flags, hashing, and low-level graphics and cryptography.
Logical versus bitwise
Bitwise operators work per bit and return an integer; logical operators (and, or, not) work on truth values and short-circuit. Confusing the two is a common bug, since & and && behave very differently.
| A | B | AND | OR | XOR |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
print(0b1100 & 0b1010) # 8 (1000)
print(0b1100 | 0b1010) # 14 (1110)
print(0b1100 ^ 0b1010) # 6 (0110)