Learn / Bit manipulation

Bits basics

Every whole number is stored as a row of bits, each worth a power of two. A few operators work on all those bits at once: AND, OR, XOR, NOT and the shifts. Knowing what each does to one bit, plus the trick n & (n - 1), answers most questions about powers of two, positions of bits, and multiplying or dividing without * or /.

How to recognise it

  • The question mentions bits, binary, powers of two, or doing arithmetic without *, / or %.
  • A value can be described by which of its bits are 1.
  • Limits are given as 32-bit integers, and overflow matters.

The idea in one picture

Write 13 in binary: 1101. Read from the right, the bits are worth 1, 2, 4 and 8, and 13 = 8 + 4 + 1. Bit operators work on every column at once, like adding in columns but without carries.

OperatorRule for one bitExample (12 is 1100, 10 is 1010)
a & b (AND)1 only if both are 11000 = 8
a | b (OR)1 if either is 11110 = 14
a ^ b (XOR)1 if they differ0110 = 6
~a (NOT)flips every bit~12 = -13 in two's complement
a << kshifts left, filling with 012 << 1 = 24
a >> kshifts right12 >> 2 = 3

Tricks worth knowing by heart

ExpressionMeaning
(n >> i) & 1bit i of n (0 or 1)
n & (n - 1)n with its lowest set bit cleared
n & -nonly the lowest set bit of n
n << k, n >> kn × 2^k, n / 2^k (rounded down for non-negative n)

Arithmetic with shifts

A product a × b is the sum of a << i over the set bits i of b. A quotient a / b is found from the top bit down: if b << i still fits into what is left of a, subtract it and set bit i of the answer. This is long division in base 2.

Common mistakes

  • Forgetting that operator precedence puts & below == in Java and C++: write (n & 1) == 1, not n & 1 == 1.
  • Shifting a 32-bit 1 by 31 or more, which overflows; use 1L or 1LL for wide shifts.
  • Treating negative numbers like positive ones: ~n and >> behave differently on them.

Problems

0 of 4 solved

Check yourself

What is 12 & 10 (12 is 1100, 10 is 1010)?

What does n & (n - 1) do?

What is 5 << 3?

Why is n > 0 and n & (n - 1) == 0 a test for a power of two?