Bit Manipulation Questions
Working directly with binary representations: bitwise operators (AND, OR, XOR, NOT, shifts, rotates) and how they differ from the logical operators, masking, two's complement and sign extension, endianness, and classic bit tricks (popcount, parity, leading and trailing zeros, lowest and highest set bit, power-of-two tests and rounding, Gray code, bit reversal, swapping without a temporary, and finding unique or missing elements with XOR). Covers bitsets and bit-vectors (including rank and select, set operations, and bitmap-based counting and sieving), packing and unpacking fields into words, protocol headers and bit-level streams, C bitfields and their portability limits, bitmask enumeration of subsets, maximum XOR and Hamming distance, SIMD and table-driven popcount, branchless arithmetic and when it pays off, overflow detection with bit operations, and integer square root by bitwise methods. Especially relevant where memory and cycles are constrained. Excludes general number theory and modular arithmetic, device register programming, Bloom filters and hash design, and cryptographic primitives, which are covered elsewhere.
You have two versions of a hot function, one with a data-dependent branch and one branchless. How would you decide which to ship? Describe what you would measure, what input distributions matter and how the answer can flip across CPUs.
Sample Answer
Direct answer
Decide by measurement on representative data, on every CPU model you actually deploy to, and default to the branchy version unless the data is shown to be unpredictable. A branchless version trades a cost that depends on the data (mispredicted jumps) for a fixed cost on every call (extra instructions, and often a longer dependency chain: a sequence of instructions where each needs the previous one's result, so they cannot overlap). Which side wins depends on how predictable the branch is, so no single winner exists in the abstract.
The mechanism in the order it happens
- A conditional branch is a jump taken or not depending on data. To keep the pipeline full, the CPU predicts the direction and starts executing down the guessed path before the data is known (speculative execution).
- If the guess was right, the branch costs almost nothing. If wrong (a misprediction), the speculative work is discarded and the pipeline restarts. The penalty is many cycles and grows with pipeline depth.
- A branchless version computes both outcomes or uses a conditional select (an instruction such as
cmovon x86 orcselon Arm that picks one of two registers) or a mask. It never mispredicts, but it always executes the extra instructions, and the result now depends on the data instead of on a guess. If the next iteration needs this result, it must wait for it. A well-predicted branch lets the CPU run ahead of that dependency; branchless code cannot.
A running minimum shows the difference. Take the values 5, 3, 8, 2, 9, with best starting at the largest possible value, and the loop if (x < best) best = x; against best = (x < best) ? x : best; compiled to a conditional select. The value of best after each element is 5, 3, 3, 2, 2, so the branch is taken at 5, 3 and 2 and not taken at 8 and 9. In the branchless form every compare needs the best produced by the previous select, so the five steps form one chain and take five compare-and-select latencies one after the other, however the data looks. In a long array the minimum changes rarely, so in the branchy form the predictor settles on "no update" and the CPU starts each next compare with the old best at once; the chain exists only along the rare updates, and the price is a flush each time the guess is wrong (in this short example, a predictor that guesses "no update" is wrong at 5, 3 and 2).
A break-even model, with stated parameters
Let P be the misprediction penalty in cycles, m the misprediction rate, and D the extra cycles per call that the branchless version costs. Branchy costs about m * P extra per call; branchless costs about D. Branchless wins when m > D / P.
With example parameters P = 15 and D = 3 (chosen to show the shape of the calculation, not measured on any CPU), the break-even is m = 3 / 15 = 20%. For random data where the branch is taken with probability q, even a best-case guess of the more common direction mispredicts at rate min(q, 1 - q):
| Branch taken with probability q | Lowest possible mispredict rate (independent random data) | Expected penalty m * P (cycles) | Branchless cost D | Winner at these parameters |
|---|---|---|---|---|
| 0.50 | 50% | 7.5 | 3 | branchless |
| 0.25 | 25% | 3.75 | 3 | branchless |
| 0.10 | 10% | 1.5 | 3 | branchy |
| 0.01 | 1% | 0.15 | 3 | branchy |
For independent random data no predictor can do better than min(q, 1 - q), so the table gives the best case the branchy version can hope for, and the winners above hold only for that kind of data. Real predictors use history, so data with runs, sorted order or short repeating patterns mispredicts far less than min(q, 1 - q), and the branchy version then looks better than the table says.
What to measure
- Mispredict rate and time together. Wall-clock time of the whole hot function over many runs (report median and spread), measured after a warm-up (a few untimed runs so caches, the predictor and the CPU clock speed reach steady state) and with the process pinned to one core (fixed to run only there, so the operating system does not move it between cores with different caches or speeds), plus the hardware counters for branches and branch misses. On Linux,
perf statreports them as thebranchesandbranch-missesevents, and-r Nrepeats the command and prints the mean and standard deviation. The mispredict rate isbranch-misses / branches: for example 250,000 misses out of 1,000,000 branches (illustrative numbers) is 25%, to be compared with the break-even rateD / Pfrom the model above. A timing difference without the counters does not tell you why. - The generated code of both versions. The source shape does not decide the machine code: in a check with GCC 14.2 on aarch64 at
-O2, a mask-based clamp and a ternary clamp compiled to the samecselsequence. If the compiler turned your branchless C back into a branch, or your branchy C into a conditional select, you are comparing the wrong things. - End-to-end, not only the microbenchmark. A tight loop over a small array trains the predictor on the very pattern in the benchmark, which production never sees.
- Tail latency if it matters. Tail latency is the slowest few percent of calls (for example the 99th percentile), which is what a service level objective often constrains. The branchy version has a bimodal cost (two clusters: cheap when predicted, expensive when mispredicted), so its tail is worse than its average; branchless has a flat one.
Input distributions that matter
| Distribution | Branchy | Why |
|---|---|---|
| Always the same way, or sorted so the branch flips once | Excellent | Predicted almost perfectly |
| Short periodic pattern | Usually good | History-based predictors learn it |
| Independent random 50/50 | Poor | Nothing to learn |
| Skewed, 1% to the rare side | Good, with rare spikes | Rare side mispredicts, common side is free |
| Data that changes shape over time (phases, different tenants) | Varies | Predictor retrains at each change |
| Adversarial or attacker-controlled | Can be forced to its worst | Relevant for latency guarantees |
Benchmark on a sample of production data, and also on sorted, shuffled, all-same and rare-case-heavy versions of it, so you know the range and not only the average.
How the answer can flip across CPUs
- Pipeline depth and recovery time: a larger
Pfavours branchless. - Predictor quality: newer cores predict longer patterns, so data that mispredicted on an older core may be learned on a newer one, shrinking
m. - Width and conditional-select cost: a core that issues many instructions per cycle makes the extra instructions (
D) cheap; the latency and throughput of conditional-select instructions differ between microarchitectures (the internal design of a CPU core: its pipeline depth, issue width and predictor, which change between CPU generations and vendors even when the instruction set is the same). - Dependency chains: if the output feeds the next iteration (a running minimum, a state machine), branchless puts the whole computation on the critical path (the longest chain of dependent instructions, which sets the minimum time for the loop) while the branchy version speculates past it, as the running-minimum steps above show; this effect is also microarchitecture dependent.
- Compiler and flags: a different compiler version or
-Olevel can change which one you actually get.
Recommendation
Ship the branchy version unless data from the real workload shows a mispredict rate above the break-even for the slowest CPU model in the fleet and the branchless version wins there by more than run-to-run noise. If the two versions are within noise on some models and one wins clearly on others, ship the one that is not worse anywhere; if that is impossible, pick by dispatching at startup (choosing the version once when the program starts, based on the detected CPU model) only with a benchmark that proves the split. Constant-time execution for secret data is a different reason to go branchless and decides the question regardless of speed: a branch on a secret value takes a different time depending on the secret, which an attacker can measure, so cryptographic code avoids secret-dependent branches even where they are faster.
Pitfalls
- Choosing from one microbenchmark with one data pattern.
- Reading a speedup on one CPU as universal.
- Counting only instructions: instruction count rises for the branchless version and still can be faster.
- Ignoring the compiler: the two source versions may compile to the same code.
Every value in an integer array appears exactly twice except one that appears once. Find it in O(n) time and O(1) extra space, and explain why the method works.
Sample Answer
The idea
XOR (^) combines two bits and gives 1 only when they differ. It has three properties that solve this problem:
a ^ a = 0: a value cancels itself.a ^ 0 = a: zero changes nothing.- XOR is commutative and associative: commutative means
a ^ b = b ^ a(swapping operands changes nothing), associative means(a ^ b) ^ c = a ^ (b ^ c)(how you group them changes nothing). Together they let you reorder and regroup a whole array freely.
So if you XOR every element together, each value that appears twice cancels to 0 wherever it sits in the array, and what is left is 0 ^ single = single. For [4, 1, 2, 1, 2] the result is 4 ^ (1 ^ 1) ^ (2 ^ 2) = 4 ^ 0 ^ 0 = 4.
Why the obvious approaches are not enough
| Approach | Time | Extra space |
|---|---|---|
| Count with a dictionary or set | O(n) | O(n) |
| Sort, then compare neighbours | O(n log n) | O(1) to O(n), depending on the sort |
| XOR of everything | O(n) | O(1) |
The dictionary works but uses memory proportional to the number of distinct values, which the question rules out. Sorting breaks the O(n) time. XOR needs one integer and one pass.
Code
from functools import reduce
from operator import xor
def find_single(nums: list[int]) -> int:
result = 0
for x in nums:
result ^= x
return result
def find_single_traced(nums: list[int]) -> int:
result = 0
print(f"{'x':>3} {'x binary':>9} {'running xor':>12}")
for x in nums:
result ^= x
print(f"{x:>3} {x:>9b} {result:>7} = {result:b}")
return result
def find_two_singles(nums: list[int]) -> tuple[int, int]:
both = find_single(nums) # a ^ b, because every pair cancels
low = both & -both # lowest set bit of a ^ b: a and b differ there
a = 0
for x in nums:
if x & low: # this half holds exactly one of the two
a ^= x
return a, both ^ a
print(find_single_traced([4, 1, 2, 1, 2]))
print(find_single([7]), find_single([-3, 5, -3]), find_single([0, 9, 0]))
print(reduce(xor, [4, 1, 2, 1, 2]))
import random
from collections import Counter
random.seed(11)
for _ in range(500):
odd = random.randint(-20, 20)
others = [v for v in range(-20, 21) if v != odd]
pairs = random.sample(others, random.randint(0, 12))
data = pairs + pairs + [odd]
random.shuffle(data)
counts = Counter(data)
assert counts[odd] == 1 and find_single(data) == odd
print("checks passed")
data = [1, 2, 1, 3, 2, 5]
both = find_single(data)
low = both & -both
print(f"both = {both:b}, low = {low:b}")
print("with the bit set:", [x for x in data if x & low], "without:", [x for x in data if not x & low])
print(find_two_singles(data))
Output:
x x binary running xor
4 100 4 = 100
1 1 5 = 101
2 10 7 = 111
1 1 6 = 110
2 10 4 = 100
4
7 5 9
4
checks passed
both = 110, low = 10
with the bit set: [2, 3, 2] without: [1, 1, 5]
(3, 5)
Reading the output
The table is the real running XOR after each element. 4 gives 100. XOR with 1 gives 101 (5). XOR with 2 gives 111 (7). The second 1 flips bit 0 back, giving 110 (6). The second 2 flips bit 1 back, giving 100 (4). The pairs undid themselves and the unpaired 4 remains. The next line shows the edge cases: a single element returns itself, [-3, 5, -3] gives 5 (negative numbers work because XOR acts on the bit pattern and the pair still cancels), and [0, 9, 0] gives 9. functools.reduce with operator.xor is the same fold in one line. The last check compares the function with a Counter on 500 random arrays (fixed seed) that contain pairs plus one unpaired value, shuffled.
Complexity
Time O(n): one pass with one XOR per element. Space O(1): a single integer, no recursion and no auxiliary list. Each XOR is constant time for values that fit in a machine word.
Edge cases and mistakes
- A one-element array returns that element. An empty array returns 0, which only matters if the contract allows empty input; here exactly one value is unpaired, so the input is never empty.
- The method relies on the pairing guarantee. If a value can appear three times, or two different values appear once, the XOR is a mix and the result is wrong. With exactly two unpaired values
aandbthe XOR isa ^ b; to separate them, take any set bit of that XOR (for example the lowest,x & -x), split the array by that bit, and XOR each half. A set bit ofa ^ bis a position whereaandbdiffer, so exactly one of them has it, and each pair lands entirely in one half (both copies share that bit). Take[1, 2, 1, 3, 2, 5], where 3 and 5 are unpaired. The XOR of everything is3 ^ 5 = 110(6). Its lowest set bit is10(2). The elements with that bit set are[2, 3, 2], whose XOR is 3; the others are[1, 1, 5], whose XOR is 5. The last lines of the output showboth = 110, low = 10, those two groups, and the result(3, 5)fromfind_two_singles. - Using addition and subtraction ("2 times the sum of the set minus the sum of the array") needs a set, so it fails the O(1) space requirement.
Running the code
python single.py
What is endianness and how does it affect serialising a 32-bit integer to bytes or reading it from a network packet? Write code that writes and reads a 32-bit value in a fixed byte order independent of the host.
Sample Answer
What endianness is
Memory and network packets hold bytes, but a 32-bit integer has four of them. Endianness is the order in which those bytes are laid out. The most significant byte (MSB) carries the biggest digits of the number; the least significant byte (LSB) the smallest.
| Order | First byte stored | 0x0A0B0C0D in memory |
|---|---|---|
| big-endian | MSB | 0A 0B 0C 0D |
| little-endian | LSB | 0D 0C 0B 0A |
Two words used below: the host is the machine running your program and the wire is the byte sequence in the packet or file. Most desktop, phone and server CPUs run little-endian. Internet protocol headers carry multi-byte fields in big-endian order, called network byte order (POSIX provides htonl and ntohl to convert). A byte array that arrives from a network or a file has a defined order that does not care what CPU reads it.
How it affects serialising and parsing
If you copy the in-memory bytes of an integer into a packet (memcpy(buf, &v, 4), or *(uint32_t *)buf = v), the packet's byte order silently becomes the host's. A little-endian sender and a big-endian receiver then disagree on every field. Casting a packet buffer to uint32_t * to read it is worse: it reads the host's order, can fault on a misaligned address on some CPUs, and breaks C's aliasing rules (the compiler may assume a uint32_t * never points at uint8_t data), which is undefined behaviour (the C standard places no requirement on what the program then does, so the compiler may assume it never happens, and the result can be a crash, a wrong value, or a value that looks right). A misaligned address is one that is not a multiple of the type's size: a uint32_t is expected to start at an address divisible by 4, and a packet buffer may start anywhere.
The host-independent fix: shifts
Shifts and masks act on the value of a number, not on how the CPU stores it. v >> 24 is always the most significant byte of v, on any machine. For the value 0x0A0B0C0D: v >> 24 is 0x0A; v >> 16 is 0x0A0B, and & 0xFF (keep only the low byte) leaves 0x0B; v >> 8 is 0x0A0B0C, giving 0x0C after the mask; v itself ends in 0x0D. The cast (uint8_t) keeps only the low 8 bits, so it does that masking for you. Those four bytes in that order are the big-endian form on any host. So write each byte out by value, and rebuild the value from bytes by value:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void put_u32_be(uint8_t out[4], uint32_t v) {
out[0] = (uint8_t)(v >> 24);
out[1] = (uint8_t)(v >> 16);
out[2] = (uint8_t)(v >> 8);
out[3] = (uint8_t)v;
}
uint32_t get_u32_be(const uint8_t in[4]) {
return ((uint32_t)in[0] << 24) | ((uint32_t)in[1] << 16) |
((uint32_t)in[2] << 8) | (uint32_t)in[3];
}
void put_u32_le(uint8_t out[4], uint32_t v) {
out[0] = (uint8_t)v;
out[1] = (uint8_t)(v >> 8);
out[2] = (uint8_t)(v >> 16);
out[3] = (uint8_t)(v >> 24);
}
uint32_t get_u32_le(const uint8_t in[4]) {
return (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
}
/* The tempting version: the uint8_t is promoted to a signed int before << 24. */
uint32_t get_u32_be_buggy(const uint8_t in[4]) {
return (uint32_t)(in[0] << 24 | in[1] << 16 | in[2] << 8 | in[3]);
}
static void show(const char *label, const uint8_t b[4]) {
printf("%-22s %02X %02X %02X %02X\n", label, b[0], b[1], b[2], b[3]);
}
int main(void) {
uint32_t v = 0x0A0B0C0Du;
uint8_t be[4], le[4], host[4];
put_u32_be(be, v);
put_u32_le(le, v);
memcpy(host, &v, 4);
show("big-endian (network)", be);
show("little-endian", le);
show("raw host memory", host);
printf("read back BE %08X, LE %08X\n", get_u32_be(be), get_u32_le(le));
printf("BE bytes read as LE: %08X\n", get_u32_le(be));
srand(7);
for (int i = 0; i < 100000; i++) {
uint32_t r = ((uint32_t)rand() << 16) ^ (uint32_t)rand() ^ ((uint32_t)rand() << 31);
uint8_t a[4], b[4];
put_u32_be(a, r);
put_u32_le(b, r);
if (get_u32_be(a) != r || get_u32_le(b) != r || a[0] != b[3] || a[3] != b[0]) {
printf("FAIL %08X\n", r);
return 1;
}
}
uint32_t edges[] = {0u, 0xFFFFFFFFu, 0x80000000u, 1u};
for (int i = 0; i < 4; i++) {
uint8_t a[4];
put_u32_be(a, edges[i]);
if (get_u32_be(a) != edges[i]) { printf("FAIL edge\n"); return 1; }
}
printf("round trips ok\n");
uint8_t high[4] = {0x80, 0x00, 0x00, 0x01};
printf("buggy read of 80 00 00 01: %08X\n", get_u32_be_buggy(high));
return 0;
}
Output
Compiled with gcc -std=c11 -Wall -Wextra -fsanitize=undefined (GCC 14.2, aarch64 Linux, a little-endian host), stdout is:
big-endian (network) 0A 0B 0C 0D
little-endian 0D 0C 0B 0A
raw host memory 0D 0C 0B 0A
read back BE 0A0B0C0D, LE 0A0B0C0D
BE bytes read as LE: 0D0C0B0A
round trips ok
buggy read of 80 00 00 01: 80000001
The raw host memory line is the only host-dependent line: a big-endian machine would print 0A 0B 0C 0D there. The last line, buggy read, comes from undefined behaviour: on this build the bytes 80 00 00 01 happen to come back as 80000001, but the C standard does not promise that, and another compiler, optimisation level or CPU may print a different value or compile the function differently. The two serialisers print the same bytes on every host. "BE bytes read as LE" shows the symptom of an order mismatch: 0A0B0C0D arrives as 0D0C0B0A.
UBSan (the undefined-behaviour sanitizer, a set of run-time checks that -fsanitize=undefined adds) also writes this line to stderr, from the deliberately wrong get_u32_be_buggy:
endian_io.c:32:29: runtime error: left shift of 128 by 24 places cannot be represented in type 'int'
The common mistake the sanitizer caught
in[0] << 24 looks fine, but C first promotes uint8_t (widens any type narrower than int) to a signed int before the shift, and 0x80 << 24 is 2^31, which does not fit in a 32-bit int, so it is undefined behaviour in C. The correct-looking printed value is the trap: the program does not fail visibly, so only the sanitizer message (or a different compiler) reveals the bug, and code like this can break after a compiler upgrade. Cast to uint32_t first, as get_u32_be does. Other mistakes: using htonl on a buffer of bytes instead of a value, reading a signed field by shifting into an int (read as uint32_t, then convert), and assuming sizeof(int) is 4 (use uint32_t).
Complexity and edge cases
Each function does a fixed handful of shifts and ORs: O(1) time, O(1) space. The run checks 100,000 random values plus 0, 1, 0x80000000 and 0xFFFFFFFF for a round trip through both orders, and that the big- and little-endian outputs are byte reversals of each other. No host-specific code is involved, so the same source runs unchanged on a big-endian target.
Running the code
gcc -std=c11 -Wall -Wextra -fsanitize=undefined -o endian_io endian_io.c && ./endian_io
A hot loop extracts bits from words and branches on each one, and profiling shows heavy branch misprediction. Refactor it to reduce mispredictions and improve instruction-level parallelism, and explain why each change helps.
Sample Answer
What is wrong
The hot loop visits every bit of every word and takes a conditional branch on its value. A branch misprediction is what happens when the CPU guesses the direction of a conditional jump (so it can keep fetching instructions ahead of time) and guesses wrong: the speculative work is thrown away and the pipeline restarts, which costs many cycles (the exact number depends on the CPU's pipeline depth). If the bit values look random, no predictor can guess them, so a large share of the 64 branches per word are mispredicted. Predictors learn patterns (all ones, alternating, runs); they cannot learn noise.
A concrete version of the loop, extracting the position of every set bit (as a bitmap index scan would: a database technique that keeps one bit per row for a condition and lists the rows whose bit is 1):
size_t positions_branchy(const uint64_t *w, size_t nwords, uint32_t *out) {
size_t n = 0;
for (size_t k = 0; k < nwords; k++)
for (int i = 0; i < 64; i++)
if ((w[k] >> i) & 1) out[n++] = (uint32_t)(k * 64 + i);
return n;
}
Compiled with gcc -O2 -S (GCC 14.2, aarch64) the inner loop contains tbz x2, 0, ... (test one bit and branch) on the data bit, and the store and n++ sit behind it, so the branch is real in the generated code on this platform.
Two refactors, and why each helps
Fix 1: visit only the set bits. x & (x - 1) clears the lowest set bit, and count-trailing-zeros (ctz, the index of the lowest set bit) tells you which bit that was. Looping while (x) runs once per set bit, so work scales with the number of ones instead of 64 per word, and there is no branch on an individual bit's value. The remaining branch is the loop condition, which is taken once per set bit and then falls out: a variable trip count (the number of times the loop body runs, here different for every word). Its outcome changes only around the end of each word, instead of on up to 64 data bits per word.
Fix 2: make the store unconditional. Always write the candidate position to out[n], then advance by the bit: n += (w[k] >> i) & 1. If the bit is 0 the next iteration overwrites the same slot. For the low four bits of 0b0101 (bits 0 and 2 set), the printed trace shows: i=0 writes out[0]=0 and the set bit moves n to 1; i=1 writes out[1]=1 but n stays 1; i=2 overwrites out[1] with 2 and n becomes 2; i=3 writes out[2]=3 and n stays 2. The kept results are out[0..2) = 0 2; the stray value in out[2] lies past n and is ignored. There is no data-dependent branch at all (the only branch left is the fixed 64-iteration loop). The cost is one store per bit. The output buffer needs nwords * 64 entries, one per bit: before the last bit is processed n is at most nwords * 64 - 1, so the last write lands on index nwords * 64 - 1, even when every bit is set. In the generated code, the tbz is gone and replaced by and x2, x2, 1 and add x0, x0, x2.
Instruction-level parallelism (ILP), the CPU executing several independent instructions in the same cycle, is helped in three ways. In fix 2 the shift, mask and store for different i do not depend on each other; only the running count n forms a one-instruction chain (a dependency chain: each add needs the previous result, so those adds cannot overlap). Fewer mispredictions also means fewer times the CPU throws away instructions it had already started on later iterations, which is lost parallel work. For fix 1 across words, the chain x &= x - 1 is serial inside a word; to overlap words, compute each word's output offset with popcount (the offset of word k+1 is the offset of word k plus its popcount) so the extraction loops of two or more words become independent chains that the CPU can interleave. For two words, the first with 4 set bits (the word traced below) and the second with bits 1 and 2 set, the second word's results start at out[0 + 4], so positions_ctz_pair below writes both words in one loop and the output is 0 9 11 63 65 66, the same as processing the words one after the other.
Code, with proof the versions agree
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Original: one data-dependent branch per bit. Writes the position of every set bit. */
size_t positions_branchy(const uint64_t *w, size_t nwords, uint32_t *out) {
size_t n = 0;
for (size_t k = 0; k < nwords; k++)
for (int i = 0; i < 64; i++)
if ((w[k] >> i) & 1) out[n++] = (uint32_t)(k * 64 + i);
return n;
}
/* Fix 1: visit only the set bits. The loop runs popcount(word) times. */
size_t positions_ctz(const uint64_t *w, size_t nwords, uint32_t *out) {
size_t n = 0;
for (size_t k = 0; k < nwords; k++) {
uint64_t x = w[k];
while (x) {
out[n++] = (uint32_t)(k * 64 + (unsigned)__builtin_ctzll(x));
x &= x - 1; /* clear the lowest set bit */
}
}
return n;
}
/* Fix 2: fixed trip count, no branch on the data. out needs room for nwords * 64 entries. */
size_t positions_store_always(const uint64_t *w, size_t nwords, uint32_t *out) {
size_t n = 0;
for (size_t k = 0; k < nwords; k++)
for (int i = 0; i < 64; i++) {
out[n] = (uint32_t)(k * 64 + i); /* always store; slot n is overwritten unless the bit is set */
n += (w[k] >> i) & 1;
}
return n;
}
/* Fix 1 for two words at a time: word k+1 starts writing at out[n + popcount(word k)], so the two
extraction chains do not depend on each other and the CPU can overlap them. */
size_t positions_ctz_pair(const uint64_t *w, size_t nwords, uint32_t *out) {
size_t n = 0, k = 0;
for (; k + 1 < nwords; k += 2) {
size_t n0 = n, n1 = n + (size_t)__builtin_popcountll(w[k]);
uint64_t x0 = w[k], x1 = w[k + 1];
while (x0 && x1) {
out[n0++] = (uint32_t)(k * 64 + (unsigned)__builtin_ctzll(x0));
out[n1++] = (uint32_t)((k + 1) * 64 + (unsigned)__builtin_ctzll(x1));
x0 &= x0 - 1; x1 &= x1 - 1;
}
while (x0) { out[n0++] = (uint32_t)(k * 64 + (unsigned)__builtin_ctzll(x0)); x0 &= x0 - 1; }
while (x1) { out[n1++] = (uint32_t)((k + 1) * 64 + (unsigned)__builtin_ctzll(x1)); x1 &= x1 - 1; }
n = n1;
}
for (; k < nwords; k++) { /* odd word count: last word alone */
uint64_t x = w[k];
while (x) { out[n++] = (uint32_t)(k * 64 + (unsigned)__builtin_ctzll(x)); x &= x - 1; }
}
return n;
}
/* Fix 2 on four bits, printing each step (the real function does this for 64 bits). */
static void trace_store_always(uint64_t word) {
uint32_t out[8] = {0};
size_t n = 0;
for (int i = 0; i < 4; i++) {
int bit = (int)((word >> i) & 1);
out[n] = (uint32_t)i;
printf(" i=%d bit=%d writes out[%zu]=%d, n becomes %zu\n", i, bit, n, i, n + (size_t)bit);
n += (size_t)bit;
}
printf(" kept results: n=%zu, out[0..n) =", n);
for (size_t j = 0; j < n; j++) printf(" %u", out[j]);
printf("\n");
}
static uint64_t rng_state = 0x9E3779B97F4A7C15ULL;
static uint64_t next_random(void) { /* xorshift64, fixed seed */
rng_state ^= rng_state << 13; rng_state ^= rng_state >> 7; rng_state ^= rng_state << 17;
return rng_state;
}
/* Misses of a "repeat the previous outcome" rule: a crude stand-in for a hardware predictor. */
static uint64_t last_outcome_misses_branchy(const uint64_t *w, size_t nwords) {
uint64_t miss = 0; int prev = 0;
for (size_t k = 0; k < nwords; k++)
for (int i = 0; i < 64; i++) { int b = (int)((w[k] >> i) & 1); miss += (b != prev); prev = b; }
return miss;
}
static uint64_t last_outcome_misses_ctz(const uint64_t *w, size_t nwords) {
uint64_t miss = 0; int prev = 1;
for (size_t k = 0; k < nwords; k++) {
uint64_t x = w[k];
for (;;) {
int again = x != 0; /* outcome of the while condition */
miss += (again != prev); prev = again;
if (!again) break;
x &= x - 1;
}
}
return miss;
}
int main(void) {
/* one word, traced */
uint64_t word = (1ULL << 0) | (1ULL << 9) | (1ULL << 11) | (1ULL << 63);
printf("word = 0x%016llX\n", (unsigned long long)word);
uint64_t x = word;
while (x) {
unsigned p = (unsigned)__builtin_ctzll(x);
printf(" x=0x%016llX ctz=%2u -> emit %2u\n", (unsigned long long)x, p, p);
x &= x - 1;
}
printf("fix 2 on the low 4 bits of 0b0101:\n");
trace_store_always(5);
uint64_t pair_in[2] = {word, 0x6ULL}; /* second word has bits 1 and 2 set */
uint32_t pair_out[8] = {0};
size_t pn = positions_ctz_pair(pair_in, 2, pair_out);
printf("two words, offsets 0 and %d, positions:", __builtin_popcountll(word));
for (size_t j = 0; j < pn; j++) printf(" %u", pair_out[j]);
printf("\n");
size_t nwords = 4096;
uint64_t *w = malloc(nwords * sizeof *w);
uint32_t *a = malloc(nwords * 64 * sizeof *a);
uint32_t *b = malloc(nwords * 64 * sizeof *b);
uint32_t *d = malloc(nwords * 64 * sizeof *d);
uint32_t *e = malloc(nwords * 64 * sizeof *e);
int percents[] = {50, 5, 99, 100};
for (unsigned t = 0; t < 4; t++) {
for (size_t k = 0; k < nwords; k++) {
w[k] = 0;
for (int i = 0; i < 64; i++) if (next_random() % 100 < (uint64_t)percents[t]) w[k] |= 1ULL << i;
}
size_t n1 = positions_branchy(w, nwords, a);
size_t n2 = positions_ctz(w, nwords, b);
size_t n3 = positions_store_always(w, nwords, d);
size_t n4 = positions_ctz_pair(w, nwords, e);
int same = n1 == n2 && n2 == n3 && n3 == n4 && memcmp(a, b, n1 * sizeof *a) == 0 &&
memcmp(a, d, n1 * sizeof *a) == 0 && memcmp(a, e, n1 * sizeof *a) == 0;
printf("density %3d%%: set bits %6zu, all four agree: %s\n", percents[t], n1, same ? "yes" : "NO");
printf(" data-dependent branch executions: branchy %zu, ctz loop %zu, store_always 0\n",
nwords * 64, n1 + nwords);
printf(" last-outcome misses: branchy %llu, ctz loop %llu\n",
(unsigned long long)last_outcome_misses_branchy(w, nwords),
(unsigned long long)last_outcome_misses_ctz(w, nwords));
}
free(w); free(a); free(b); free(d); free(e);
return 0;
}
Each density block prints two kinds of count. The data-dependent branch executions are how many times a branch on a data value runs. The last-outcome misses are the number of times a branch's outcome differs from its previous outcome: a crude, deterministic stand-in for a hardware predictor that guesses "same as last time". The random numbers come from xorshift64, a tiny pseudo-random generator started from a fixed seed so every run is identical. Compiled with gcc -std=c11 -Wall -Wextra -fsanitize=undefined,address -fno-sanitize-recover=undefined in a python:3.12 container (GCC 14.2, aarch64), no warnings or sanitizer reports, it prints:
word = 0x8000000000000A01
x=0x8000000000000A01 ctz= 0 -> emit 0
x=0x8000000000000A00 ctz= 9 -> emit 9
x=0x8000000000000800 ctz=11 -> emit 11
x=0x8000000000000000 ctz=63 -> emit 63
fix 2 on the low 4 bits of 0b0101:
i=0 bit=1 writes out[0]=0, n becomes 1
i=1 bit=0 writes out[1]=1, n becomes 1
i=2 bit=1 writes out[1]=2, n becomes 2
i=3 bit=0 writes out[2]=3, n becomes 2
kept results: n=2, out[0..n) = 0 2
two words, offsets 0 and 4, positions: 0 9 11 63 65 66
density 50%: set bits 131068, all four agree: yes
data-dependent branch executions: branchy 262144, ctz loop 135164, store_always 0
last-outcome misses: branchy 131124, ctz loop 8191
density 5%: set bits 13162, all four agree: yes
data-dependent branch executions: branchy 262144, ctz loop 17258, store_always 0
last-outcome misses: branchy 25078, ctz loop 7911
density 99%: set bits 259493, all four agree: yes
data-dependent branch executions: branchy 262144, ctz loop 263589, store_always 0
last-outcome misses: branchy 5255, ctz loop 8191
density 100%: set bits 262144, all four agree: yes
data-dependent branch executions: branchy 262144, ctz loop 266240, store_always 0
last-outcome misses: branchy 1, ctz loop 8191
The last-outcome count is not a measured misprediction count: real counts come from the CPU's performance counters on the target machine. It shows the shape clearly. At 50% density the per-bit branch changes direction about every other time (131,124 of 262,144 executions), while the ctz loop changes direction about twice per word (8,191 changes for 4,096 words). At 99% density the original branch is almost always taken (5,255 changes), and at 100% it changes once, so there is little to fix and the other versions do relatively more work (store_always stores 64 slots per word whatever the data).
Worked trace
The first lines of the output trace one word, 0x8000000000000A01 (bits 0, 9, 11 and 63 set): x & (x - 1) strips the lowest bit each round, ctz reads 0, 9, 11, 63 in turn, and the loop runs exactly four times for four set bits, then x is 0 and the loop exits.
Complexity
The branchy and store_always loops are O(nwords * 64) (64 iterations per word whatever the data); the ctz loop is O(nwords + number of set bits). Extra space is O(1) besides the output.
Edge cases and common mistakes
- A zero word:
ctzloop does no iterations;store_alwaysstill does 64 stores. - All-ones word:
ctzloop does 64 iterations, each with its dependentx &= x - 1, so it can be slower than the original when the branch is perfectly predictable. __builtin_ctzll(0)is undefined, which is why the call sits insidewhile (x).store_alwaysneedsnwords * 64output slots (one per bit, the all-ones case is in the run above); a buffer of exactly the number of set bits is overrun whenever the final bit is 0, because the slot after the last result is written before the bit is read.- Do not claim a speedup from the source alone: the compiler may already have changed the loop (check the assembly), and the winner depends on the density of the data (see the counts above). Measure on real data with hardware counters before shipping.
Running the code
gcc -std=c11 -Wall -Wextra -fsanitize=undefined,address -fno-sanitize-recover=undefined bit_positions.c -o bit_positions
./bit_positions
Save the listing as bit_positions.c. It needs GCC or Clang for __builtin_ctzll. Add -O2 -S to inspect the generated assembly of the four positions_ functions.
Compare std::bitset<N>, std::vector<bool> and a hand-rolled packed bit array in C++. When would you choose each, considering memory, speed of set, test and scan, and API surprises?
Sample Answer
Direct answer
All three can store one bit per flag, but they differ in who decides the size and how you scan. Use std::bitset<N> when N is a compile-time constant and you want a small, bounds-aware, operator-rich type. Use std::vector<bool> only when the size is decided at run time and you accept its quirks and slower, bit-at-a-time access. Use a hand-rolled array of 64-bit words when you need run-time size plus fast scanning, word-level operations, serialization or SIMD (single instruction, multiple data) access to the raw words.
What each one is
std::bitset<N> | std::vector<bool> | Packed array of uint64_t words | |
|---|---|---|---|
| Size | Fixed: N is a template parameter (a value written in angle brackets that the compiler fixes when it compiles), known at compile time | Run time, can resize and push_back | Run time (you write the resize) |
| Memory | About N/8 bytes rounded up to a whole word, no heap allocation by itself (1,000,000 bits: 125,000 bytes in the run below) | Packing is allowed but not guaranteed ("implementation defined" per cppreference); libstdc++ (the C++ standard library that ships with GCC) packs it, and the object also holds heap bookkeeping | Exactly ceil(n/64) words, 15,625 words (125,000 bytes) for 1,000,000 bits |
| Set / test | set, reset, flip, test, [], and whole-set &, |, ^, ~, shifts | v[i], flip, push_back; no whole-set operators | You write them: shift and mask, one machine instruction each |
| Scan for set bits | No iterator for set bits in the standard interface; loop test(i) over every index, or use a library extension | Same: loop over every index | Skip an all-zero word in one comparison, then peel set bits with countr_zero (count trailing zeros: the number of 0 bits below the lowest 1 bit, which is that bit's index) |
| Count set bits | count() | std::count (the standard does not promise a word-at-a-time version) | popcount per word, 15,625 calls for a million bits |
| Fits when | Flag sets known at build time; hash-table sized masks; small sieve | Run-time size, speed not critical, convenience matters | Large sparse sets, hot scans, set algebra, interop with raw words |
API surprises (each one is real, shown below)
std::vector<bool>is not a normal container.operator[]returns a small proxy object (a stand-in that remembers the word and bit; in libstdc++ it is a pointer to the word plus a mask, which is why the run printssizeof(proxy) = 16: 8 bytes each), sobool* p = &v[0]andauto& r = v[0]do not compile. In GCC 14.2 the errors arecannot convert 'std::vector<bool>::reference*' to 'bool*'andcannot bind non-const lvalue reference ... to an rvalue. It has nodata(), and generic code written forvector<T>that takes references breaks. Writes go through the proxy and do reach the vector.- Because it may not be a real container, concurrent writes to two different elements are a data race (two threads touching the same memory location with at least one write and no synchronisation, which makes the program's behaviour undefined; here they share a word), unlike
vector<int>where each element is its own location. bitset::operator[]does not check bounds;test(i)does and throwsstd::out_of_range.to_ulong()throwsstd::overflow_errorwhen a bit above the width ofunsigned longis set.- N cannot be chosen at run time: a
bitset<N>with a variable N does not compile, and a very large N can overflow the stack, the fixed-size memory area for local variables (8 MiB per thread is the common Linux default, checked withulimit -sin the test container; 125,000 bytes here is fine, tens of megabytes is not). - Both standard types miss "find next set bit". libstdc++'s
_Find_firstand_Find_nextdo it forbitset, but they are non-standard extensions (only GCC's library provides them), so portable code rolls its own.
How the word-skipping scan works
Take a 128-bit set with bits 3, 64 and 127 on. Stored as two 64-bit words, word 0 is 0x8 (only bit 3) and word 1 is 0x8000000000000001 (bits 0 and 63, which are flags 64 and 127). The loop in for_each_set does this:
| Step | Word | countr_zero(w) | Flag index wi * 64 + countr_zero | w &= w - 1 leaves |
|---|---|---|---|---|
| word 0, first bit | 0x8 | 3 | 0 * 64 + 3 = 3 | 0 (loop ends) |
| word 1, first bit | 0x8000000000000001 | 0 | 1 * 64 + 0 = 64 | 0x8000000000000000 |
| word 1, second bit | 0x8000000000000000 | 63 | 1 * 64 + 63 = 127 | 0 (loop ends) |
w & (w - 1) clears the lowest set bit because subtracting 1 turns that bit into 0 and every zero below it into 1, so AND zeroes exactly that run. A word that is already 0 skips the inner loop at once, which is the word skipping.
Code
#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <vector>
// Hand-rolled packed bit array: dynamic size, raw 64-bit words, fast scan.
class PackedBits {
public:
explicit PackedBits(std::size_t n) : size_(n), words_((n + 63) / 64, 0) {}
void set(std::size_t i) { words_[i >> 6] |= (std::uint64_t{1} << (i & 63)); }
void reset(std::size_t i) { words_[i >> 6] &= ~(std::uint64_t{1} << (i & 63)); }
bool test(std::size_t i) const { return (words_[i >> 6] >> (i & 63)) & 1; }
std::size_t count() const {
std::size_t c = 0;
for (auto w : words_) c += std::popcount(w);
return c;
}
// Visit set bits, skipping empty words; counts how many words were examined.
template <class F> void for_each_set(F f, std::size_t& words_seen) const {
for (std::size_t wi = 0; wi < words_.size(); ++wi) {
++words_seen;
for (std::uint64_t w = words_[wi]; w; w &= w - 1)
f(wi * 64 + std::countr_zero(w));
}
}
std::size_t word_count() const { return words_.size(); }
private:
std::size_t size_;
std::vector<std::uint64_t> words_;
};
int main() {
constexpr std::size_t N = 1'000'000;
std::bitset<N> fixed;
std::vector<bool> dyn(N);
PackedBits packed(N);
std::cout << "sizeof(bitset<1000000>) = " << sizeof(fixed) << " bytes\n";
std::cout << "PackedBits words = " << packed.word_count() << " x 8 = "
<< packed.word_count() * 8 << " bytes\n";
for (std::size_t i : {3u, 64u, 999'999u}) { fixed.set(i); dyn[i] = true; packed.set(i); }
std::cout << "counts: " << fixed.count() << " " << packed.count() << "\n";
// API surprises
std::vector<bool> small{true, false};
auto r = small[1]; // a proxy object, not a bool
r = true; // writes through to the vector
std::cout << "proxy write-through: small[1] = " << small[1]
<< ", sizeof(proxy) = " << sizeof(r) << "\n";
// bool* p = &small[0]; // does not compile: no bool* exists
// auto& ref = small[0]; // does not compile: cannot bind a temporary
try { fixed.test(N); } catch (const std::out_of_range& e) { std::cout << "bitset::test(N) throws out_of_range\n"; }
try { fixed.to_ulong(); } catch (const std::overflow_error&) { std::cout << "to_ulong throws overflow_error (bit 999999 set)\n"; }
// Scan cost: bit-by-bit test versus word skipping, counted not timed
std::size_t bit_tests = 0, hits = 0;
for (std::size_t i = 0; i < N; ++i) { ++bit_tests; hits += dyn[i]; }
std::size_t words_seen = 0, found = 0;
packed.for_each_set([&](std::size_t) { ++found; }, words_seen);
std::cout << "bit-by-bit: " << bit_tests << " tests, " << hits << " hits\n";
std::cout << "word skip : " << words_seen << " words, " << found << " hits\n";
}
Run output (GCC 14.2, aarch64 Linux, libstdc++, compiled as in the last section; the sizes are implementation facts that can differ on another standard library):
sizeof(bitset<1000000>) = 125000 bytes
PackedBits words = 15625 x 8 = 125000 bytes
counts: 3 3
proxy write-through: small[1] = 1, sizeof(proxy) = 16
bitset::test(N) throws out_of_range
to_ulong throws overflow_error (bit 999999 set)
bit-by-bit: 1000000 tests, 3 hits
word skip : 15625 words, 3 hits
The scan numbers are counts of work, not times. Testing every index does 1,000,000 tests for 3 hits (the bit-by-bit line); the word-skipping scan examines 15,625 words (the word skip line) and peels each of the 3 set bits with countr_zero and w &= w - 1 (clear the lowest set bit). That is 64 times fewer examinations when the set is sparse, and the advantage shrinks toward nothing when most words contain bits, because every set bit still costs one step.
Choosing
- Compile-time size and mostly set operations (union, test, count):
std::bitset<N>. It does the word loops for you andcount()is built in. - Run-time size, simple use, not performance critical:
std::vector<bool>, understanding the proxy and that you must not rely on its layout. - Large, hot, scan-heavy, or needing raw words (network headers, memory-mapped files, SIMD, atomic words for concurrent updates): the packed
uint64_tarray. Concurrency is a real reason: withstd::atomic<uint64_t>words you canfetch_orone bit atomically (an OR that completes as one indivisible step, so no other thread sees a half-done update), which neither standard type offers. - What would flip the choice: if N is known only at run time but you want the
bitsetoperator set, use a library dynamic bitset (for exampleboost::dynamic_bitsetfrom the Boost C++ libraries), which cppreference itself names as the alternative.
Complexity and pitfalls
set,test,resetare O(1) for all three. Whole-set operations andcountare O(N/64) word operations forbitsetand the hand-rolled array (O(N) per-bit work forvector<bool>without a specialised algorithm).- The shipped scan is O(N/64 + k) for k set bits; testing every index is O(N).
- Space: N/8 bytes rounded up to a word, for the bitset and the packed array.
- Pitfalls:
i >> 6andi & 63needuint64_t{1}(not1) before the shift, or the shift happens in a 32-bitintand is undefined for any index of 32 or more; forgetting the last partial word's unused bits when you invert (~) and then count; mistakingvector<bool>for a container ofbool.
Running the code
g++ -std=c++20 -Wall -Wextra -O2 -fsanitize=undefined bitset_compare.cpp -o bitsets && ./bitsets
Needs C++20 for <bit> (std::popcount, std::countr_zero).
Unlock Full Question Bank
Get access to all Bit Manipulation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.