Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Bit Manipulation

Masks, XOR tricks and whole sets packed into one machine word.

A 64-bit integer is not one number to your processor; it is 64 independent switches that it can flip, combine and count in a single instruction. Treat it that way and a whole set of up to 64 items fits in one register, "is this a power of two?" becomes one line, and finding the one unpaired value among millions takes a single XOR pass.

What you’ll learn

  • Read and write integers as bit patterns, including negative numbers in two's complement, and predict the result of AND, OR, XOR, NOT and shifts.
  • Test, set, clear and toggle bit ii, and prove that x&(x−1)x\mathbin{\&}(x-1) clears and x&(−x)x\mathbin{\&}(-x) isolates the lowest set bit.
  • Use XOR's self-cancellation to find unpaired elements, and know when it fails.
  • Represent subsets as bitmasks and enumerate all 2n2^n of them in O(2nn)O(2^n n) time.
  • Recognize bitmask problems from their constraints, and avoid the precedence, width and sign bugs of C++ and Python.

Numbers are rows of bits

An unsigned ww-bit integer xx is a row of bits xw−1…x1x0x_{w-1}\dots x_1x_0 with x=∑ixi2ix=\sum_i x_i2^i. Bit 0 is the least significant. Bitwise operators act on every position at once and independently:

OperatorBit ii of the resultExample on 12=1100212=1100_2 and 10=1010210=1010_2
AND a & b1 if both bits are 110002=81000_2=8
OR a | b1 if either bit is 111102=141110_2=14
XOR a ^ b1 if the bits differ01102=60110_2=6
NOT ~athe opposite bitin 8 bits, 11110011211110011_2
Shifts a << k, a >> kbit i−ki-k, or bit i+ki+k12≪1=2412\ll1=24, 12≫2=312\gg2=3
A left shift by kk multiplies by 2k2^k (while nothing falls off the top); a right shift by kk divides by 2k2^k and rounds down.

Negative numbers use two's complement: in ww bits, −x-x is stored as 2w−x2^w-x, which is the same as ∼x+1\mathord{\sim}x+1. The top bit then acts as the sign, the range is −2w−1-2^{w-1} to 2w−1−12^{w-1}-1, and ordinary addition works unchanged for both signs. In 8 bits, −1-1 is 11111111211111111_2 and −6-6 is 11111010211111010_2.

Single bits, and the lowest set bit

TaskExpressionOn x=10112x=1011_2, i=2i=2
Test bit ii(x >> i) & 100
Set bit iix | (1 << i)111121111_2
Clear bit iix & ~(1 << i)101121011_2 (already clear)
Toggle bit iix ^ (1 << i)111121111_2

Two expressions do something more surprising: they find the lowest set bit without any loop.

DerivationWhy x & (x − 1) and x & (−x) work
  1. x=y 1 0⋯0⏟kx=y\,1\,\underbrace{0\cdots0}_{k}

    Let x≠0x\ne0. Its binary form ends with a 1 followed by k≥0k\ge0 zeros; call the part above it yy:

  2. x−1=y 0 1⋯1⏟k⟹x&(x−1)=y 0 0⋯0⏟kx-1=y\,0\,\underbrace{1\cdots1}_{k}\qquad\Longrightarrow\qquad x\mathbin{\&}(x-1)=y\,0\,\underbrace{0\cdots0}_{k}

    Subtracting 1 borrows through the trailing zeros: the lowest 1 becomes 0 and the zeros become 1s. AND with xx keeps yy and clears everything from the lowest 1 down:

  3. −x=y‾ 1 0⋯0⏟k⟹x&(−x)=0⋯0 1 0⋯0⏟k=2k-x=\overline{y}\,1\,\underbrace{0\cdots0}_{k}\qquad\Longrightarrow\qquad x\mathbin{\&}(-x)=0\cdots0\,1\,\underbrace{0\cdots0}_{k}=2^k

    In two's complement −x=∼x+1-x=\mathord{\sim}x+1. NOT flips everything, and the +1+1 carries through the kk ones back to the lowest position, so only that bit agrees with xx:

Consequences you will use constantly:

  • Power of two: x>0x>0 and x&(x−1)=0x\mathbin{\&}(x-1)=0, since only powers of two have a single set bit.
  • Popcount loop: while x: x &= x - 1; count += 1 runs once per set bit, not once per bit (Wegner, 1960).
  • Fenwick trees jump by i & -i to move between the ranges they store (see Fenwick Trees in Depth).
Predict before you look

How many times does the loop while x: x &= x - 1 run when it starts at x=180=101101002x=180=10110100_2?

Show the answer

4

Each iteration clears exactly one set bit: 10110100→10110000→10100000→10000000→010110100\to10110000\to10100000\to10000000\to0. Four set bits, four iterations, compared with eight for a loop that inspects every bit.

XOR: the operation that undoes itself

XOR is addition modulo 2 in every bit position, so it inherits clean algebra: x⊕x=0x\oplus x=0, x⊕0=xx\oplus0=x, and it is commutative and associative. XOR a whole list together, in any order, and every value that appears an even number of times cancels.

  • The unpaired element: if every value appears twice except one, the XOR of the list is that value. O(n)O(n) time, O(1)O(1) extra space, no hash set.
  • The missing number: if nn distinct values come from 0..n0..n with one missing, XOR all indices 0..n0..n with all values; everything present cancels.
  • Parity: the XOR of the bits of xx says whether popcount⁡(x)\operatorname{popcount}(x) is odd.
  • Addition without carries: a+b=(a⊕b)+2 (a&b)a+b=(a\oplus b)+2\,(a\mathbin{\&}b). XOR is the sum, AND marks the carries.
python
from functools import reduce
from operator import xor

print(reduce(xor, [7, 3, 5, 3, 7, 9, 5]))      # 9: every other value cancels

def missing(values):                           # n distinct values from 0..n
    acc = len(values)                          # the index n has no partner
    for i, v in enumerate(values):
        acc ^= i ^ v
    return acc

print(missing([4, 0, 1, 5, 2]))                # 3
Check your understanding

Every value in a list appears three times except one value, which appears once: [6,1,6,6,9,1,1][6,1,6,6,9,1,1]. What does XOR-ing the whole list give, and how do you find the single value?

  1. It gives 99, the single value, as in the pairs case
  2. It gives 6⊕1⊕9=146\oplus1\oplus9=14; count each bit position modulo 3 instead
  3. It gives 00; sort the list instead
  4. It gives 99; XOR always isolates the value with an odd count
Show the answer

B. It gives 6⊕1⊕9=146\oplus1\oplus9=14; count each bit position modulo 3 instead

A value appearing three times survives XOR once (x⊕x⊕x=xx\oplus x\oplus x=x), so the result is 6⊕1⊕9=146\oplus1\oplus9=14. Counting, for each bit position, how many numbers have that bit set and taking the count modulo 3 leaves exactly the bits of the single value: 99.

Sets in a word: bitmasks

A subset SS of {0,1,…,n−1}\{0,1,\dots,n-1\} is the bitmask m=∑i∈S2im=\sum_{i\in S}2^i: bit ii is set exactly when item ii is in the set. Set operations become single instructions:

Set operationBitmask expression
i∈Si\in S(m >> i) & 1
S∪TS\cup T, S∩TS\cap T, S∖TS\setminus Ts | t, s & t, s & ~t
complement within nn items((1 << n) - 1) ^ s
∣S∣\abs{S}popcount(s)
S⊆TS\subseteq T(s & t) == s
all subsets of nn itemsfor m in range(1 << n)

Counting from 00 to 2n−12^n-1 visits every subset exactly once, because each number has a unique binary form. That is the cleanest brute force over subsets: 2n2^n masks with O(n)O(n) work each, O(2nn)O(2^n n). By the course's rule of thumb (about 10810^8 simple operations per second, and always a rule of thumb), it fits for nn up to about 20 to 25: 220⋅20≈2.1×1072^{20}\cdot20\approx2.1\times10^7, but 225⋅25≈8.4×1082^{25}\cdot25\approx8.4\times10^8.

python
weights = [3, 4, 5, 2]
values = [30, 50, 60, 15]
cap = 9
best = 0
for m in range(1 << len(weights)):             # every subset of the 4 items
    w = sum(weights[i] for i in range(len(weights)) if m >> i & 1)
    if w <= cap:
        v = sum(values[i] for i in range(len(weights)) if m >> i & 1)
        best = max(best, v)
print(best)                                    # 110: items 1 and 2, mask 0110

A brute-force knapsack over masks: correct for any nn, fast enough for n≤20n\le20 or so. Shifts bind tighter than &, so m >> i & 1 means (m >> i) & 1 in Python and C++ alike; the trap is ==, which binds tighter than & in C and C++ but not in Python.

LanguagePopcountLowest set bit indexNotes
C++ (GCC, Clang)__builtin_popcount, __builtin_popcountll__builtin_ctz, __builtin_ctzllcompiler builtins; ctz and clz of 0 are undefined
C++20std::popcountstd::countr_zeroin <bit>, for unsigned types
Python 3.10+x.bit_count()(x & -x).bit_length() - 1bin(x).count('1') on older versions
JavaInteger.bitCount, Long.bitCountInteger.numberOfTrailingZerosalso Long versions

Recognizing it

Signals that point to bit manipulation:

  • n≤20n\le20 (or so) and "choose any subset": enumerate 2n2^n masks, or run a dynamic program over masks.
  • "Every value appears twice except…", "find the missing number", toggles and parity: XOR.
  • Powers of two, "the number of 1 bits", binary representations in the statement: the lowest-set-bit tricks and popcount.
  • Sums or counts over all pairs of an XOR or AND: treat each bit position separately and add up its contribution.
Problem (in brief)Key ideaCost
Find the value that appears once when all others appear twiceXOR the whole listO(n)O(n), O(1)O(1) space
Best subset of n≤20n\le20 items under a constraintEnumerate masks 0 .. 2^n - 1O(2nn)O(2^n n)
Number of 1 bits of every integer 0..n0..nb[i]=b[i≫1]+(i&1)b[i]=b[i\gg1]+(i\mathbin{\&}1)O(n)O(n)
Sum of ai⊕aja_i\oplus a_j over all pairsBit kk contributes onesk⋅zerosk⋅2k\mathit{ones}_k\cdot\mathit{zeros}_k\cdot2^kO(nlog⁡V)O(n\log V)
Maximum XOR of two numbers in an arrayGreedy bit by bit in a binary trieO(nlog⁡V)O(n\log V)
VV is the largest value. The last row is the subject of Binary Tries & Maximum XOR.
Check your understanding

You must split n=18n=18 tasks between two machines so that their total running times are as close as possible. Which approach fits the constraints?

  1. Try all 18!18! orders of the tasks
  2. Sort the tasks and use two pointers
  3. Enumerate all 2182^{18} bitmasks of tasks for the first machine
  4. A difference array
Show the answer

C. Enumerate all 2182^{18} bitmasks of tasks for the first machine

Each mask is one split, so 218=262,1442^{18}=262{,}144 masks with O(n)O(n) work each (about 4.7×1064.7\times10^6 steps) solve it exactly. Only which machine gets each task matters, not the order.

cpp
#include <bit>                                     // C++20
#include <cstdio>

int main() {
    int x = 6;
    if ((x & 1) == 0) std::puts("even");          // parentheses: == binds tighter than &
    long long big = 1LL << 40;                     // 1 << 40 would shift a 32-bit int: undefined
    unsigned m = 0b10110100u;
    int pc = __builtin_popcount(m);                // GCC/Clang builtin: 4
    int tz = __builtin_ctz(m);                     // lowest set bit index: 2 (undefined for 0)
    int pc20 = std::popcount(m);                   // portable C++20: 4
    bool pow2 = m != 0 && (m & (m - 1)) == 0;      // false: 180 is not a power of two
    std::printf("%lld %d %d %d %d\n", big, pc, tz, pc20, pow2);
}

Prints even, then 1099511627776 4 2 4 0.

Key takeaways

  • Bitwise operators work on every bit position independently; shifts multiply or divide by powers of two, and ww-bit negatives are stored in two's complement as 2w−x=∼x+12^w-x=\mathord{\sim}x+1.
  • x&(x−1)x\mathbin{\&}(x-1) clears the lowest set bit and x&(−x)x\mathbin{\&}(-x) isolates it: power-of-two tests, popcount loops and Fenwick trees all rest on these two identities.
  • XOR is its own inverse: XOR-ing a list cancels every value with an even count, which finds unpaired and missing values in O(n)O(n) time and O(1)O(1) space; values with other multiplicities need per-bit counts.
  • A bitmask is a subset; for m in range(1 << n) enumerates all 2n2^n of them, practical up to n≈20n\approx20–2525, and set operations become single instructions.
  • In C and C++, parenthesize bitwise expressions, write 1LL << k for wide shifts, never shift by the type's width or more, and avoid ctz/clz of zero.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For an integer x>0x>0, what does the condition (x & (x - 1)) == 0 test?

  1. xx is even
  2. xx is odd
  3. xx is a power of two
  4. xx has its top bit set
Show the answer

C. xx is a power of two

x&(x−1)x\mathbin{\&}(x-1) clears the lowest set bit. The result is 0 exactly when that was the only set bit, that is, when x=2kx=2^k.

Question 2

What is the 8-bit two's-complement pattern of −6-6?

  1. 10000110210000110_2
  2. 11111001211111001_2
  3. 11111010211111010_2
  4. 00000110200000110_2
Show the answer

C. 11111010211111010_2

−6=28−6=250=111110102-6=2^8-6=250=11111010_2, equivalently ∼000001102+1=111110012+1\mathord{\sim}00000110_2+1=11111001_2+1.

Question 3

In C++, int x = 6; if (x & 1 == 0) puts("even"); What happens?

  1. It prints "even", because 6 is even
  2. It never prints: the condition is x & (1 == 0), which is x & 0, always 0
  3. It does not compile
  4. It prints "even" only for odd x
Show the answer

B. It never prints: the condition is x & (1 == 0), which is x & 0, always 0

In C and C++, == has higher precedence than &. The condition becomes x & 0, which is 0 for every x. Compilers warn about it (-Wparentheses); write (x & 1) == 0.

Question 4

A loop for m in range(1 << n) does O(n)O(n) work per subset. Using the rule of thumb of about 10810^8 simple operations per second in C++, for which nn does it comfortably fit in one second?

  1. n=20n=20
  2. n=30n=30
  3. n=40n=40
  4. n=64n=64
Show the answer

A. n=20n=20

220⋅20≈2.1×1072^{20}\cdot20\approx2.1\times10^7 steps fit easily. 230⋅30≈3.2×10102^{30}\cdot30\approx3.2\times10^{10} is several minutes, and n=40n=40 or 6464 is hopeless: use meet in the middle or a smarter idea.

Go deeper

Further reading

  • H. S. Warren Jr., Hacker's Delight, 2nd ed. (Addison-Wesley, 2012).
  • D. E. Knuth, The Art of Computer Programming, Vol. 4A: Combinatorial Algorithms, Part 1 (Addison-Wesley, 2011), §7.1.3, "Bitwise tricks and techniques".
  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 10, "Bit manipulation" (free online).
  • S. E. Anderson, Bit Twiddling Hacks, Stanford University (a long-maintained collection of tricks with explanations).