Know this before you start: “Binary numbers and AND / OR / XOR”
Binary numbers and AND, OR, XOR
Every integer is a row of bits. AND keeps bits set in both, OR in either, XOR in exactly one: fast tools for flags, masks and tricks.
The idea
13 in binary is 1101: 8 + 4 + 0 + 1. Bitwise operators work on each position separately.
AND (&) is 1 only where both are 1: it tests or clears bits. OR (|) is 1 where either is 1: it sets bits. XOR (^) is 1 where they differ: it toggles bits and cancels pairs.
bin(x) shows the bits in Python, and x & 1 tells you whether x is odd.
See it step by step
a = 12 (1100) and b = 10 (1010)
- a & b = 1000 = 8 (bits in both)
- a | b = 1110 = 14 (bits in either)
- a ^ b = 0110 = 6 (bits in exactly one)
In code (Python)
a, b = 12, 10
print(bin(a), bin(b)) # 0b1100 0b1010
print(a & b, a | b, a ^ b) # 8 14 6
print(13 & 1, 12 & 1) # 1 0: odd, even
def bit_is_set(x, i):
return (x >> i) & 1 == 1
print(bit_is_set(13, 2), bit_is_set(13, 1)) # True FalseEach operation: O(1).
When you'll use it
- Counting bits, power of two checks, subsets as bitmasks, flags, single number problems.
Common mistakes
- Operator precedence in Java/C++: write (x & 1) == 1 with parentheses.
- Forgetting Python ints are unbounded (no 32-bit overflow).