Android & iPhone apps are coming soon. Log in for a plan and reminders made for you →

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)

  1. a & b = 1000 = 8 (bits in both)
  2. a | b = 1110 = 14 (bits in either)
  3. 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 False

Each 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).

Practise it: Bit Manipulation & Math

You'll use it again in

Go further