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 , and prove that clears and 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 of them in 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 -bit integer is a row of bits with . Bit 0 is the least significant. Bitwise operators act on every position at once and independently:
| Operator | Bit of the result | Example on and |
|---|---|---|
AND a & b | 1 if both bits are 1 | |
OR a | b | 1 if either bit is 1 | |
XOR a ^ b | 1 if the bits differ | |
NOT ~a | the opposite bit | in 8 bits, |
Shifts a << k, a >> k | bit , or bit | , |
Negative numbers use two's complement: in bits, is stored as , which is the same as . The top bit then acts as the sign, the range is to , and ordinary addition works unchanged for both signs. In 8 bits, is and is .
Single bits, and the lowest set bit
| Task | Expression | On , |
|---|---|---|
| Test bit | (x >> i) & 1 | |
| Set bit | x | (1 << i) | |
| Clear bit | x & ~(1 << i) | (already clear) |
| Toggle bit | x ^ (1 << i) |
Two expressions do something more surprising: they find the lowest set bit without any loop.
Let . Its binary form ends with a 1 followed by zeros; call the part above it :
Subtracting 1 borrows through the trailing zeros: the lowest 1 becomes 0 and the zeros become 1s. AND with keeps and clears everything from the lowest 1 down:
In two's complement . NOT flips everything, and the carries through the ones back to the lowest position, so only that bit agrees with :
Consequences you will use constantly:
- Power of two: and , since only powers of two have a single set bit.
- Popcount loop:
while x: x &= x - 1; count += 1runs once per set bit, not once per bit (Wegner, 1960). - Fenwick trees jump by
i & -ito move between the ranges they store (see Fenwick Trees in Depth).
How many times does the loop while x: x &= x - 1 run when it starts at ?
Show the answer
4
Each iteration clears exactly one set bit: . 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: , , 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. time, extra space, no hash set.
- The missing number: if distinct values come from with one missing, XOR all indices with all values; everything present cancels.
- Parity: the XOR of the bits of says whether is odd.
- Addition without carries: . XOR is the sum, AND marks the carries.
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])) # 3Every value in a list appears three times except one value, which appears once: . What does XOR-ing the whole list give, and how do you find the single value?
- It gives , the single value, as in the pairs case
- It gives ; count each bit position modulo 3 instead
- It gives ; sort the list instead
- It gives ; XOR always isolates the value with an odd count
Show the answer
B. It gives ; count each bit position modulo 3 instead
A value appearing three times survives XOR once (), so the result is . 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: .
Sets in a word: bitmasks
A subset of is the bitmask : bit is set exactly when item is in the set. Set operations become single instructions:
| Set operation | Bitmask expression |
|---|---|
(m >> i) & 1 | |
| , , | s | t, s & t, s & ~t |
| complement within items | ((1 << n) - 1) ^ s |
popcount(s) | |
(s & t) == s | |
| all subsets of items | for m in range(1 << n) |
Counting from to visits every subset exactly once, because each number has a unique binary form. That is the cleanest brute force over subsets: masks with work each, . By the course's rule of thumb (about simple operations per second, and always a rule of thumb), it fits for up to about 20 to 25: , but .
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 0110A brute-force knapsack over masks: correct for any , fast enough for 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.
| Language | Popcount | Lowest set bit index | Notes |
|---|---|---|---|
| C++ (GCC, Clang) | __builtin_popcount, __builtin_popcountll | __builtin_ctz, __builtin_ctzll | compiler builtins; ctz and clz of 0 are undefined |
| C++20 | std::popcount | std::countr_zero | in <bit>, for unsigned types |
| Python 3.10+ | x.bit_count() | (x & -x).bit_length() - 1 | bin(x).count('1') on older versions |
| Java | Integer.bitCount, Long.bitCount | Integer.numberOfTrailingZeros | also Long versions |
Recognizing it
Signals that point to bit manipulation:
- (or so) and "choose any subset": enumerate 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 idea | Cost |
|---|---|---|
| Find the value that appears once when all others appear twice | XOR the whole list | , space |
| Best subset of items under a constraint | Enumerate masks 0 .. 2^n - 1 | |
| Number of 1 bits of every integer | ||
| Sum of over all pairs | Bit contributes | |
| Maximum XOR of two numbers in an array | Greedy bit by bit in a binary trie |
You must split tasks between two machines so that their total running times are as close as possible. Which approach fits the constraints?
- Try all orders of the tasks
- Sort the tasks and use two pointers
- Enumerate all bitmasks of tasks for the first machine
- A difference array
Show the answer
C. Enumerate all bitmasks of tasks for the first machine
Each mask is one split, so masks with work each (about steps) solve it exactly. Only which machine gets each task matters, not the order.
#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 -bit negatives are stored in two's complement as .
- clears the lowest set bit and 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 time and space; values with other multiplicities need per-bit counts.
- A bitmask is a subset;
for m in range(1 << n)enumerates all of them, practical up to –, and set operations become single instructions. - In C and C++, parenthesize bitwise expressions, write
1LL << kfor wide shifts, never shift by the type's width or more, and avoidctz/clzof zero.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For an integer , what does the condition (x & (x - 1)) == 0 test?
- is even
- is odd
- is a power of two
- has its top bit set
Show the answer
C. is a power of two
clears the lowest set bit. The result is 0 exactly when that was the only set bit, that is, when .
What is the 8-bit two's-complement pattern of ?
Show the answer
C.
, equivalently .
In C++, int x = 6; if (x & 1 == 0) puts("even"); What happens?
- It prints "even", because 6 is even
- It never prints: the condition is
x & (1 == 0), which isx & 0, always 0 - It does not compile
- 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.
A loop for m in range(1 << n) does work per subset. Using the rule of thumb of about simple operations per second in C++, for which does it comfortably fit in one second?
Show the answer
A.
steps fit easily. is several minutes, and or is hopeless: use meet in the middle or a smarter idea.
Go deeper
- Subsets as Bitmasks · Enumerating subsets and submasks, the 3ⁿ bound and sums over subsets.
- XOR Bases: Linear Algebra over GF(2) · Maximum-XOR subsets and Gaussian elimination on bits.
- Bit-Parallel Algorithms · Bitsets, word-level parallelism, Shift-And matching and the Four Russians.
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).