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.
A binary protocol packs a 3-bit version, 13-bit type, 20-bit length and further non-byte-aligned fields into a 64-bit header. Write pack and unpack code, and explain how you would make it correct on both big- and little-endian machines.
Sample Answer
The idea in plain words
There are two separate problems. The first is the bit layout: which bits of a 64-bit number belong to which field. That is shifts and masks (a mask is a number with 1s in the positions you want to keep, ANDed with a value to cut everything else off). The second is byte order (endianness): a 64-bit integer occupies eight bytes in memory, and a little-endian machine stores the least significant byte first while a big-endian machine stores the most significant byte first. A protocol fixes one order on the wire (the sequence of bytes actually sent over the network or written to a file), and code that copies the integer's memory straight into the packet gets the right bytes on one kind of machine and the reversed bytes on the other.
The fix for the second problem is to never look at how the host stores the integer. Build the 64-bit value with shifts, which operate on the number and not on its memory image, and write the bytes out one at a time with a shift per byte. The same source then produces the same bytes on every machine.
The layout
The question names three fields (3, 13 and 20 bits) and "further non-byte-aligned fields" that fill the other 28 bits. Here those further fields are flags (5 bits), channel (11 bits) and sequence (12 bits). The wire order is most significant byte first (big-endian, also called network byte order, the convention most internet protocols use), and the first field sits in the top bits.
| Field | Width | Bits (63 is the top) | Largest value |
|---|---|---|---|
| version | 3 | 63..61 | 7 |
| type | 13 | 60..48 | 8191 |
| length | 20 | 47..28 | 1,048,575 |
| flags | 5 | 27..23 | 31 |
| channel | 11 | 22..12 | 2047 |
| sequence | 12 | 11..0 | 4095 |
3 + 13 + 20 + 5 + 11 + 12 = 64. Fields such as type and length straddle byte boundaries (type covers the last 5 bits of byte 0 and all 8 bits of byte 1), which is why you cannot just copy bytes.
Approach
- Pack: reject any field that does not fit its width (otherwise an oversized value spills into its neighbour). Widen each field to
uint64_tfirst, because shifting a 16-bit or 32-bit value left by 48 or 61 would otherwise happen in a narrower type and lose bits or be undefined. Shift each field to its position and OR them together. - Serialize: byte
iof the packet is(word >> (56 - 8*i)) & 0xFF, so byte 0 carries bits 63..56. - Unpack: rebuild the word with
w = (w << 8) | bytefor bytes 0 to 7, then for each field shift down and mask.
Because both directions use the value of the integer and never its memory layout, the result does not depend on the machine.
Code (C)
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Wire layout, most significant bit first (bit 63 is the first bit on the wire):
version 3 | type 13 | length 20 | flags 5 | channel 11 | sequence 12 = 64 bits */
typedef struct {
uint8_t version; /* 3 bits */
uint16_t type; /* 13 bits */
uint32_t length; /* 20 bits */
uint8_t flags; /* 5 bits */
uint16_t channel; /* 11 bits */
uint16_t sequence; /* 12 bits */
} Header;
#define VERSION_SHIFT 61
#define TYPE_SHIFT 48
#define LENGTH_SHIFT 28
#define FLAGS_SHIFT 23
#define CHANNEL_SHIFT 12
#define SEQUENCE_SHIFT 0
#define MASK(bits) ((UINT64_C(1) << (bits)) - 1)
/* Returns 0 on success, -1 if any field does not fit its width. */
static int pack_header(const Header *h, uint8_t out[8]) {
if (h->version > MASK(3) || h->type > MASK(13) || h->length > MASK(20) ||
h->flags > MASK(5) || h->channel > MASK(11) || h->sequence > MASK(12))
return -1;
uint64_t w = ((uint64_t)h->version << VERSION_SHIFT)
| ((uint64_t)h->type << TYPE_SHIFT)
| ((uint64_t)h->length << LENGTH_SHIFT)
| ((uint64_t)h->flags << FLAGS_SHIFT)
| ((uint64_t)h->channel << CHANNEL_SHIFT)
| ((uint64_t)h->sequence << SEQUENCE_SHIFT);
for (int i = 0; i < 8; i++) /* byte 0 is the most significant byte */
out[i] = (uint8_t)(w >> (56 - 8 * i));
return 0;
}
static void unpack_header(const uint8_t in[8], Header *h) {
uint64_t w = 0;
for (int i = 0; i < 8; i++) w = (w << 8) | in[i];
h->version = (uint8_t)((w >> VERSION_SHIFT) & MASK(3));
h->type = (uint16_t)((w >> TYPE_SHIFT) & MASK(13));
h->length = (uint32_t)((w >> LENGTH_SHIFT) & MASK(20));
h->flags = (uint8_t)((w >> FLAGS_SHIFT) & MASK(5));
h->channel = (uint16_t)((w >> CHANNEL_SHIFT) & MASK(11));
h->sequence = (uint16_t)((w >> SEQUENCE_SHIFT) & MASK(12));
}
static int same(const Header *a, const Header *b) { /* field by field: struct padding is not compared */
return a->version == b->version && a->type == b->type && a->length == b->length &&
a->flags == b->flags && a->channel == b->channel && a->sequence == b->sequence;
}
static void print_bytes(const char *label, const uint8_t b[8]) {
printf("%-26s", label);
for (int i = 0; i < 8; i++) printf(" %02x", b[i]);
printf("\n");
}
static uint64_t xorshift64(uint64_t *s) {
uint64_t x = *s;
x ^= x << 13; x ^= x >> 7; x ^= x << 17;
return *s = x;
}
int main(void) {
Header h = {5, 0x1ABC, 0xABCDE, 0x15, 0x5A5, 0xF0F};
uint8_t wire[8];
pack_header(&h, wire);
print_bytes("wire bytes:", wire);
const uint8_t expected[8] = {0xba, 0xbc, 0xab, 0xcd, 0xea, 0xda, 0x5f, 0x0f};
printf("matches expected bytes: %s\n", memcmp(wire, expected, 8) == 0 ? "yes" : "no");
/* The tempting shortcut: copy the host's 64-bit integer into the buffer. */
uint64_t as_integer = 0xbabcabcdeada5f0fULL;
uint8_t naive[8];
memcpy(naive, &as_integer, 8);
print_bytes("memcpy of the integer:", naive);
Header back;
unpack_header(wire, &back);
printf("unpacked: v=%u type=0x%x len=0x%x flags=0x%x ch=0x%x seq=0x%x\n",
back.version, back.type, back.length, back.flags, back.channel, back.sequence);
Header too_big = h;
too_big.type = 1u << 13;
printf("type = 8192 rejected: %d\n", pack_header(&too_big, wire));
uint64_t seed = 7;
for (int n = 0; n < 100000; n++) {
Header a = {
(uint8_t)(xorshift64(&seed) & MASK(3)), (uint16_t)(xorshift64(&seed) & MASK(13)),
(uint32_t)(xorshift64(&seed) & MASK(20)), (uint8_t)(xorshift64(&seed) & MASK(5)),
(uint16_t)(xorshift64(&seed) & MASK(11)), (uint16_t)(xorshift64(&seed) & MASK(12))};
Header b;
uint8_t buf[8];
if (pack_header(&a, buf) != 0) return 1;
unpack_header(buf, &b);
if (!same(&a, &b)) { printf("FAIL at %d\n", n); return 1; }
}
printf("100000 random round trips: ok\n");
return 0;
}
Output on a little-endian machine (aarch64 Linux, GCC 14.2, flags as in the last section; the memcpy line differs on a big-endian CPU, as the second run shows):
wire bytes: ba bc ab cd ea da 5f 0f
matches expected bytes: yes
memcpy of the integer: 0f 5f da ea cd ab bc ba
unpacked: v=5 type=0x1abc len=0xabcde flags=0x15 ch=0x5a5 seq=0xf0f
type = 8192 rejected: -1
100000 random round trips: ok
The same program compiled and run on a big-endian machine (IBM s390x, run under an emulator, which is software that imitates that processor so a laptop can run its programs; the results are the same as on real hardware, only slower):
wire bytes: ba bc ab cd ea da 5f 0f
matches expected bytes: yes
memcpy of the integer: ba bc ab cd ea da 5f 0f
unpacked: v=5 type=0x1abc len=0xabcde flags=0x15 ch=0x5a5 seq=0xf0f
type = 8192 rejected: -1
100000 random round trips: ok
Worked trace
The test header has version = 5, type = 0x1abc, length = 0xabcde, flags = 0x15, channel = 0x5a5, sequence = 0xf0f. In binary, field by field:
| Field | Bits |
|---|---|
| version | 101 |
| type | 1101010111100 |
| length | 10101011110011011110 |
| flags | 10101 |
| channel | 10110100101 |
| sequence | 111100001111 |
Concatenated, the 64 bits are 1011101010111100101010111100110111101010110110100101111100001111. Cut that string into groups of eight bits, one group per wire byte, and read each group as hex. Fields that straddle a byte boundary are split across two rows:
| Byte | Bits | Hex | Which field bits it holds |
|---|---|---|---|
| 0 | 10111010 | ba | version 101, then the top 5 bits of type (11010) |
| 1 | 10111100 | bc | the low 8 bits of type |
| 2 | 10101011 | ab | the top 8 bits of length |
| 3 | 11001101 | cd | the next 8 bits of length |
| 4 | 11101010 | ea | the last 4 bits of length (1110), then the top 4 bits of flags (1010) |
| 5 | 11011010 | da | the last bit of flags (1), then the top 7 bits of channel (1011010) |
| 6 | 01011111 | 5f | the low 4 bits of channel (0101), then the top 4 bits of sequence (1111) |
| 7 | 00001111 | 0f | the low 8 bits of sequence |
So the word is 0xbabcabcdeada5f0f and the wire bytes are ba bc ab cd ea da 5f 0f, which is what both machines print for "wire bytes" and what the comparison against the expected bytes (computed independently from the table above) confirms.
The same integer sits in memory in two different byte orders. Addresses grow left to right, and the integer is 0xbabcabcdeada5f0f:
| Machine | addr+0 | +1 | +2 | +3 | +4 | +5 | +6 | +7 |
|---|---|---|---|---|---|---|---|---|
| big-endian (most significant byte first) | ba | bc | ab | cd | ea | da | 5f | 0f |
| little-endian (least significant byte first) | 0f | 5f | da | ea | cd | ab | bc | ba |
A reader without a big-endian machine can check this table with Python: (0xbabcabcdeada5f0f).to_bytes(8, 'big').hex(' ') and .to_bytes(8, 'little').hex(' ') print the two rows. The line "memcpy of the integer" is the endianness bug in action. Copying the memory of the 64-bit integer gives 0f 5f da ea cd ab bc ba on the little-endian machine, the bytes reversed, and the correct bytes on the big-endian machine. Code with this line passes every test on a developer laptop and fails when it meets a big-endian peer, and the other way round if it was only ever tested against a big-endian one.
Making it correct on both big- and little-endian machines
- Use shifts and masks on integer values and write bytes individually, as
pack_headerdoes. - Do not
memcpyastruct, an integer, or a C bit-field struct onto the wire. The struct has padding bytes (unused filler bytes the compiler inserts between members so each starts at a convenient address; the code compares fields one by one for that reason), a host byte order, and an implementation-defined bit-field layout. - The platform helpers (
htobe64on Linux and BSD,htonllwhere provided; both mean "convert a 64-bit host integer to big-endian") exist but are not in standard C, and their availability and spelling differ by platform. The shift loop needs nothing. - Test it on a big-endian target or an emulator, not only by reasoning: the run above shows the identical wire bytes from both. Add a fixed test vector (a known header and its eight bytes) to the unit tests so the check runs everywhere.
- Writing bytes one at a time also avoids unaligned 64-bit loads and stores (reading or writing 8 bytes at an address that is not a multiple of 8, which some processors fault on or run slowly), and avoids pointer casts that break the C aliasing rules (the rule that an object may only be accessed through a pointer of a compatible type, which lets the compiler assume otherwise-cast accesses do not overlap and can produce wrong code when you break it).
Complexity
Pack and unpack are O(1): six shifts and ORs plus an 8-iteration byte loop. No extra space beyond the 8-byte buffer.
Edge cases and common mistakes
- Oversized field values:
type = 8192is rejected (printed-1) instead of overwritinglength. - Shifting a narrow type:
h->type << 48on auint16_tis computed as anint, which is undefined or truncating; cast touint64_tfirst, as the code does. - Using
1 << nfor a mask whennis 32 or more: writeUINT64_C(1) << n. - Mixing up bit order and byte order. Byte order is about the eight bytes of the integer; the bit positions inside the integer are the same on every machine, which is why shifts are safe.
- Memcmp on structs compares padding; compare field by field.
- Reading a packet shorter than 8 bytes must be rejected before
unpack_headeris called; the function trusts its caller to supply 8 bytes. - Validation after unpack: a protocol usually also requires checking that
versionis one you support and thatlengthis not larger than the buffer you have.
Running the code
gcc -std=c11 -O2 -Wall -Wextra -fsanitize=undefined header.c -o header && ./header
Implement a compact bit set backed by an array of 64-bit words with set, clear, get and a count of set bits in a range. Then explain how you would adapt it for 10 million flags, and for a microcontroller with 64 KB of RAM.
Sample Answer
The idea in plain words
A bit set stores one yes/no flag per bit instead of one flag per byte. The array holds 64-bit words (here a word means one array element, a uint64_t that carries 64 flags). Flag number i lives in word i / 64 at bit position i % 64. Setting a flag ORs a one-bit mask into that word, clearing it ANDs with the inverted mask, and reading it shifts the word down and keeps the lowest bit. Counting the set bits in a range is a popcount (count of 1 bits in a word) over the words the range covers, with masks on the first and last words so only the bits inside the range count.
Brute force and why it is not enough
An array of booleans costs one byte per flag (10,000,000 bytes for 10 million flags), and counting a range means looking at every flag in it. The bit set is 8 times smaller and counts 64 flags per popcount. Compared with Python, where a list of True and False costs 8 bytes of pointer per entry on a 64-bit build, the difference is 64 times.
Approach
- Layout:
words[i / 64], biti % 64, where bit 0 is the least significant bit. The number of words isceil(nbits / 64). - set / clear / get: one OR, AND-NOT or shift-and-mask on one word: O(1).
- count_range(lo, hi) over positions
lo <= i < hi(half-open, so adjacent ranges never double count): visit the words fromlo / 64to(hi - 1) / 64. For each word build a mask of just the positions inside the range (a partial mask on the first and last word, all ones on the middle words), AND it with the word, and add the popcount. For the first word of a range starting at position 60 in a 64-bit word,span_mask(60, 64)is(all ones) & ~((1 << 60) - 1) = 0xF000000000000000, which keeps bits 60 to 63 and nothing below. - Iterate the set bits efficiently: for each non-zero word, repeat: isolate the lowest set bit (
x & (~x + 1), which isx & -xon an unsigned type), turn it into a position (the popcount of "lowest bit minus 1" counts the zeros below it), report it, then clear it withx &= x - 1. The cost is the number of words plus the number of set bits, not the number of bits, so a sparse set is fast to walk. Tiny example withx = 0b101000(bits 3 and 5 set, decimal 40):~x + 1is the two's complement negation-x, andx & -x = 0b001000keeps only the lowest set bit, 8. Then8 - 1 = 7 = 0b111has ones exactly below that bit, its popcount is 3, so the bit's position is 3.x &= x - 1gives40 & 39 = 32 = 0b100000, which removes bit 3, and the next round finds position 5.
Code (C)
bitset_set, bitset_clear, bitset_get and bitset_count_range are the four operations the question asks for. bitset_for_each, build_index and bitset_rank serve the scaling discussion further down, and check_against_reference is a test harness that compares everything with a plain array. The word size is a build option so the same code serves 64-bit machines and 32-bit microcontrollers. The storage is passed in by the caller, so it can come from malloc or from a static array with no heap at all. The popcount is written out (not a compiler builtin) so the code needs nothing beyond standard C. It is the SWAR (SIMD within a register) method: it counts every part of the word at once with ordinary arithmetic. Step one turns each pair of bits into the number of ones in that pair, step two adds neighbouring pairs into per-nibble (4-bit) counts, step three adds nibbles into per-byte counts, and the multiply by 0x0101...01 adds all byte counts into the top byte, which the final shift reads out. On the byte 0xB7 = 10110111: pair counts 01 10 01 10, nibble counts 3 and 3, byte count 6, and 10110111 does contain six ones.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Build with -DWORD_BITS=32 for a 32-bit microcontroller; the default is 64. */
#ifndef WORD_BITS
#define WORD_BITS 64
#endif
#if WORD_BITS == 64
typedef uint64_t word_t;
static int popcount_word(word_t x) {
x = x - ((x >> 1) & 0x5555555555555555ULL);
x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
return (int)((x * 0x0101010101010101ULL) >> 56);
}
#else
typedef uint32_t word_t;
static int popcount_word(word_t x) {
x = x - ((x >> 1) & 0x55555555u);
x = (x & 0x33333333u) + ((x >> 2) & 0x33333333u);
x = (x + (x >> 4)) & 0x0F0F0F0Fu;
return (int)((x * 0x01010101u) >> 24);
}
#endif
#define ALL_ONES ((word_t)~(word_t)0)
typedef struct {
word_t *words; /* storage supplied by the caller: malloc, static array, anything */
size_t nbits;
} Bitset;
static size_t words_needed(size_t nbits) { return (nbits + WORD_BITS - 1) / WORD_BITS; }
static void bitset_init(Bitset *b, word_t *storage, size_t nbits) {
b->words = storage;
b->nbits = nbits;
memset(storage, 0, words_needed(nbits) * sizeof(word_t));
}
static void bitset_set(Bitset *b, size_t i) { b->words[i / WORD_BITS] |= ((word_t)1 << (i % WORD_BITS)); }
static void bitset_clear(Bitset *b, size_t i) { b->words[i / WORD_BITS] &= ~((word_t)1 << (i % WORD_BITS)); }
static int bitset_get(const Bitset *b, size_t i) { return (int)((b->words[i / WORD_BITS] >> (i % WORD_BITS)) & 1u); }
/* Mask of bit positions [lo, hi) inside one word, with 0 <= lo < hi <= WORD_BITS. */
static word_t span_mask(unsigned lo, unsigned hi) {
word_t upto_hi = (hi == WORD_BITS) ? ALL_ONES : (((word_t)1 << hi) - 1);
word_t below_lo = ((word_t)1 << lo) - 1;
return upto_hi & ~below_lo;
}
static int g_trace = 0;
/* Number of set bits in positions [lo, hi). Requires lo <= hi <= nbits. */
static size_t bitset_count_range(const Bitset *b, size_t lo, size_t hi) {
if (lo >= hi) return 0;
size_t first = lo / WORD_BITS, last = (hi - 1) / WORD_BITS, total = 0;
for (size_t w = first; w <= last; w++) {
unsigned from = (w == first) ? (unsigned)(lo % WORD_BITS) : 0;
unsigned to = (w == last) ? (unsigned)((hi - 1) % WORD_BITS) + 1 : WORD_BITS;
int c = popcount_word(b->words[w] & span_mask(from, to));
if (g_trace) printf(" word %zu: bits %u..%u counted -> %d\n", w, from, to - 1, c);
total += (size_t)c;
}
return total;
}
/* Visit set bits in increasing order: cost is proportional to the number of words plus set bits. */
static size_t bitset_for_each(const Bitset *b, void (*visit)(size_t, void *), void *ctx) {
size_t visited = 0;
for (size_t w = 0; w < words_needed(b->nbits); w++) {
word_t x = b->words[w];
while (x) {
word_t lowest = x & (word_t)(~x + 1u); /* isolate the lowest set bit */
size_t index = w * WORD_BITS + (size_t)popcount_word(lowest - 1);
visit(index, ctx);
visited++;
x &= x - 1; /* clear it */
}
}
return visited;
}
/* Rank index: running count at the start of each block of 8 words. */
#define BLOCK_WORDS 8
static size_t index_entries(size_t nbits) { return (words_needed(nbits) + BLOCK_WORDS - 1) / BLOCK_WORDS; }
static void build_index(const Bitset *b, uint32_t *prefix) {
uint32_t running = 0;
size_t nwords = words_needed(b->nbits);
for (size_t w = 0; w < nwords; w++) {
if (w % BLOCK_WORDS == 0) prefix[w / BLOCK_WORDS] = running;
running += (uint32_t)popcount_word(b->words[w]);
}
}
/* Set bits in [0, i), 0 <= i <= nbits, nbits >= 1: one table read, then at most 8 words: 7 whole words and one partial word, or 8 whole words when i == nbits and nbits ends on a block boundary. */
static size_t bitset_rank(const Bitset *b, const uint32_t *prefix, size_t i) {
size_t nwords = words_needed(b->nbits);
size_t w = i / WORD_BITS;
unsigned rem = (unsigned)(i % WORD_BITS);
size_t block = (w < nwords ? w : nwords - 1) / BLOCK_WORDS;
size_t total = prefix[block];
for (size_t k = block * BLOCK_WORDS; k < w; k++) total += (size_t)popcount_word(b->words[k]);
if (rem) total += (size_t)popcount_word(b->words[w] & (((word_t)1 << rem) - 1));
return total;
}
static void print_index(size_t i, void *ctx) { (void)ctx; printf(" %zu", i); }
typedef struct { const unsigned char *ref; size_t last; int ok; } VisitCheck;
static void check_visit(size_t i, void *p) {
VisitCheck *c = p;
if (!c->ref[i] || (c->last != 0 && i <= c->last)) c->ok = 0; /* must be a set bit, strictly increasing */
c->last = i;
}
static uint64_t xorshift64(uint64_t *s) {
uint64_t x = *s;
x ^= x << 13; x ^= x >> 7; x ^= x << 17;
return *s = x;
}
static void check_against_reference(void) {
enum { N = 1000 };
word_t storage[(N + WORD_BITS - 1) / WORD_BITS];
uint32_t prefix[(N + WORD_BITS * BLOCK_WORDS - 1) / (WORD_BITS * BLOCK_WORDS)];
unsigned char ref[N] = {0};
Bitset b;
bitset_init(&b, storage, N);
uint64_t seed = 12345;
for (int op = 0; op < 5000; op++) {
size_t i = xorshift64(&seed) % N;
if (xorshift64(&seed) & 1) { bitset_set(&b, i); ref[i] = 1; }
else { bitset_clear(&b, i); ref[i] = 0; }
}
for (size_t i = 0; i < N; i++)
if (bitset_get(&b, i) != ref[i]) { printf("get mismatch at %zu\n", i); exit(1); }
build_index(&b, prefix);
size_t edges[] = {0, 1, 31, 32, 33, 63, 64, 65, 127, 128, 129, 511, 512, 513, 999, 1000};
size_t ne = sizeof edges / sizeof edges[0], checked = 0;
for (size_t x = 0; x < ne; x++)
for (size_t y = x; y < ne; y++) {
size_t want = 0;
for (size_t i = edges[x]; i < edges[y]; i++) want += ref[i];
if (bitset_count_range(&b, edges[x], edges[y]) != want) { printf("range mismatch\n"); exit(1); }
checked++;
}
for (int k = 0; k < 3000; k++) {
size_t lo = xorshift64(&seed) % (N + 1), hi = xorshift64(&seed) % (N + 1);
if (lo > hi) { size_t t = lo; lo = hi; hi = t; }
size_t want = 0;
for (size_t i = lo; i < hi; i++) want += ref[i];
if (bitset_count_range(&b, lo, hi) != want) { printf("range mismatch\n"); exit(1); }
if (bitset_rank(&b, prefix, hi) != bitset_count_range(&b, 0, hi)) { printf("rank mismatch\n"); exit(1); }
checked++;
}
VisitCheck ctx = {ref, 0, 1};
size_t visited = bitset_for_each(&b, check_visit, &ctx), want_visits = 0;
for (size_t i = 0; i < N; i++) want_visits += ref[i];
if (!ctx.ok || visited != want_visits) { printf("iteration mismatch\n"); exit(1); }
printf("checked %zu ranges and %zu visited bits against a plain array: ok\n", checked, visited);
}
int main(void) {
enum { N = 200 };
word_t storage[(N + WORD_BITS - 1) / WORD_BITS];
Bitset b;
bitset_init(&b, storage, N);
size_t on[] = {3, 64, 69, 130, 199};
for (size_t k = 0; k < sizeof on / sizeof on[0]; k++) bitset_set(&b, on[k]);
bitset_set(&b, 4);
bitset_clear(&b, 4);
printf("get(3)=%d get(4)=%d get(64)=%d\n", bitset_get(&b, 3), bitset_get(&b, 4), bitset_get(&b, 64));
printf("count_range(60, 131), word size %d:\n", WORD_BITS);
g_trace = 1;
size_t c = bitset_count_range(&b, 60, 131);
g_trace = 0;
printf(" total = %zu\n", c);
printf("set bits:");
bitset_for_each(&b, print_index, NULL);
printf("\n");
check_against_reference();
/* Memory arithmetic and a large instance: 10 million flags. */
size_t flags = 10000000;
size_t nwords = words_needed(flags), nidx = index_entries(flags);
printf("10,000,000 flags with %d-bit words: %zu words = %zu bytes, index %zu entries = %zu bytes\n",
WORD_BITS, nwords, nwords * sizeof(word_t), nidx, nidx * sizeof(uint32_t));
word_t *big = malloc(nwords * sizeof(word_t));
uint32_t *idx = malloc(nidx * sizeof(uint32_t));
if (!big || !idx) return 1;
Bitset bb;
bitset_init(&bb, big, flags);
for (size_t i = 0; i < flags; i += 3) bitset_set(&bb, i);
build_index(&bb, idx);
printf("every third flag set: count_range(0, N) = %zu, rank(N) = %zu, rank(5000000) = %zu\n",
bitset_count_range(&bb, 0, flags), bitset_rank(&bb, idx, flags), bitset_rank(&bb, idx, 5000000));
free(big);
free(idx);
/* Microcontroller case: 10,000 flags in static storage, no malloc. */
printf("10,000 flags with %d-bit words: %zu words = %zu bytes\n",
WORD_BITS, words_needed(10000), words_needed(10000) * sizeof(word_t));
return 0;
}
Output with 64-bit words:
get(3)=1 get(4)=0 get(64)=1
count_range(60, 131), word size 64:
word 0: bits 60..63 counted -> 0
word 1: bits 0..63 counted -> 2
word 2: bits 0..2 counted -> 1
total = 3
set bits: 3 64 69 130 199
checked 3136 ranges and 499 visited bits against a plain array: ok
10,000,000 flags with 64-bit words: 156250 words = 1250000 bytes, index 19532 entries = 78128 bytes
every third flag set: count_range(0, N) = 3333334, rank(N) = 3333334, rank(5000000) = 1666667
10,000 flags with 64-bit words: 157 words = 1256 bytes
Output of the same file built with -DWORD_BITS=32:
get(3)=1 get(4)=0 get(64)=1
count_range(60, 131), word size 32:
word 1: bits 28..31 counted -> 0
word 2: bits 0..31 counted -> 2
word 3: bits 0..31 counted -> 0
word 4: bits 0..2 counted -> 1
total = 3
set bits: 3 64 69 130 199
checked 3136 ranges and 499 visited bits against a plain array: ok
10,000,000 flags with 32-bit words: 312500 words = 1250000 bytes, index 39063 entries = 156252 bytes
every third flag set: count_range(0, N) = 3333334, rank(N) = 3333334, rank(5000000) = 1666667
10,000 flags with 32-bit words: 313 words = 1252 bytes
Worked trace
The demo sets bits 3, 64, 69, 130 and 199 in a 200-bit set. count_range(60, 131) asks for positions 60 to 130. With 64-bit words the code visits three words:
| Word | Positions counted | Set bits found | Count |
|---|---|---|---|
| 0 | 60 to 63 (partial: the range starts at 60) | none (bit 3 is outside) | 0 |
| 1 | 0 to 63 (the whole word, positions 64 to 127) | 64 and 69 | 2 |
| 2 | 0 to 2 (partial: the range ends at 130, so positions 128 to 130) | 130 | 1 |
The total is 3, and the iteration prints 3 64 69 130 199. With 32-bit words the same range touches four words and gives the same total, as the second output shows.
Adapting it for 10 million flags
The bit set itself needs no change at this size (the first bullet gives the memory). What changes is how quickly a range count runs and how updates are coordinated. The rank index is the fix for slow range counts; the Fenwick tree, the compressed bitmap and the atomic OR each apply to a particular workload (frequent writes, very sparse data, several writer threads).
- Memory: 10,000,000 / 64 = 156,250 words of 8 bytes = 1,250,000 bytes (about 1.2 MiB). The program prints this.
- Range counts get slow:
count_rangeis O(range / 64). For 10 million flags a query over the whole set reads 156,250 words. If you ask for many range counts, build a rank index: store the running count at the start of every block of 8 words, then a count of the firstibits (rank(i)) is one table read plus at most 8 words scanned (7 whole words and one partial word; wheniequalsnbitsandnbitsends exactly on a block boundary, 8 whole words and no partial word). A range count is thenrank(hi) - rank(lo). The index costs one 32-bit number per block: 19,532 entries = 78,128 bytes, which is 6.25 percent extra (the program prints both numbers and checksrankagainstcount_range). Choose the block size to trade index size against words scanned per query. - Updates: the index must be rebuilt, or updated for the affected block and all later blocks, after a
setorclear. If writes are frequent and range counts are frequent, use a Fenwick tree (also called a binary indexed tree: an array in which entry j stores the sum of a block of counts whose length is the lowest set bit of j, so adding to one position and summing a prefix each touch about log2(n) entries) over the word counts instead, which handles both in O(log n); the index above fits read-mostly data. - Sparse data: if only a few thousand of the 10 million flags are ever set, a sorted list of positions or a compressed bitmap (a format that stores long runs of identical words, such as all-zero stretches, as a short start-and-length record instead of every word) beats the flat bit set. Say what density you expect before choosing.
- Concurrency: setting a bit is a read-modify-write (read the whole word, change one bit, write the whole word back), so two threads setting different bits in the same word can lose one update. Use an atomic OR (C11
atomic_fetch_or, an OR that completes as one indivisible step that no other thread can interleave with) or give each thread its own words.
Adapting it for a microcontroller with 64 KB of RAM
A microcontroller is a small single-chip computer with little memory and few instructions; the changes are about sizing storage statically, matching the CPU's native word and surviving interrupts.
64 KB is 65,536 bytes, which holds at most 524,288 flags if nothing else used RAM, and the stack, the program's variables and any buffers also need it. For 10,000 flags:
- Size the storage at compile time: a static array of
(10000 + 31) / 32words. With 32-bit words that is 313 words = 1,252 bytes, about 2 percent of 64 KB (the program prints 313 and 1252 for the 32-bit build). With 64-bit words it is 157 words = 1,256 bytes. Pass the static array tobitset_init; there is nomalloc, so there is no heap fragmentation (free memory split into pieces too small to reuse) or allocation failure to handle. - Use the CPU's native word: on a 32-bit microcontroller, 64-bit shifts and ORs compile to several instructions, so
uint32_twords are faster. That is the-DWORD_BITS=32build above. - Popcount: many small microcontrollers have no popcount instruction. The SWAR version in the code (add bits in pairs, then nibbles, then bytes) needs only shifts, masks, adds and one multiply. Without a hardware multiplier (a circuit that multiplies in one step; without it a multiply costs many instructions), a 256-entry byte table kept in flash (the chip's non-volatile program memory, which survives power loss and is usually larger than RAM) trades 256 bytes of flash for the multiply: look up the popcount of each byte and add.
- Interrupts:
setandclearare read-modify-write sequences. An interrupt is a hardware signal that pauses the main program to run a handler function. If an interrupt handler and the main program touch bits in the same word, one can overwrite the other's update. Disable interrupts around the update, use an atomic operation where the hardware has one, or keep the two contexts' flags in different words. - Range checks: the code leaves out bounds checks to keep it short. On a device with no memory protection, an out-of-range index silently corrupts the next variable in RAM, so add a check or an assertion for any index that comes from outside the program.
Complexity
| Operation | Time | Extra space |
|---|---|---|
set, clear, get | O(1) | O(1) |
count_range(lo, hi) | O(1 + (hi - lo) / 64) | O(1) |
| Iterate all set bits | O(nbits / 64 + number of set bits) | O(1) |
build_index | O(nbits / 64) | one 32-bit entry per 8 words |
rank(i) with the index | O(1): one table read, then at most 8 words (7 whole and one partial, or 8 whole when i equals nbits on a block boundary) | O(1) |
The bit set itself uses ceil(nbits / 64) words.
Edge cases and common mistakes
- Shifting a plain
1:1 << 40is anintshift and overflows. Write(word_t)1 << n, which the code does everywhere. A shift count equal to the word width is undefined behaviour, which is whyspan_maskspecial-caseshi == WORD_BITS. - Empty range (
lo == hi) returns 0 and a range that ends exactly on a word boundary does not touch the next word (the code uses(hi - 1) / WORD_BITSfor the last word). - Off-by-one in the range convention: the range is half-open. A closed range
[lo, hi]iscount_range(lo, hi + 1). - Forgetting that
nbitsis not a multiple of 64: the last word has unused bits that must stay 0, or counts will include them. The code never sets them, andcount_rangemasks them off. - Index of the lowest bit:
popcount(lowest - 1)is the position, becauselowest - 1has ones exactly in the positions below it. Many compilers also offer a count-trailing-zeros builtin (it counts the zero bits below the lowest set bit, which is that bit's position) that does it in one or two instructions (GCC 14.2 emits a singlebsfon x86-64 and the pairrbit,clzon 64-bit ARM). - The run compares
get, 3,136 range counts (including every pair of boundary positions around 31, 32, 33, 63, 64, 65, 127, 128, 129, 511, 512, 513),rankand the iteration against a plain byte array on random operations, for both word sizes.
Running the code
gcc -std=c11 -O2 -Wall -Wextra -fsanitize=undefined bitset.c -o bitset && ./bitset
gcc -std=c11 -O2 -Wall -Wextra -fsanitize=undefined -DWORD_BITS=32 bitset.c -o bitset32 && ./bitset32
What is the difference between a logical and an arithmetic right shift? What does the C standard guarantee when you shift a negative signed value right, and how would you write code that behaves the same on every compiler?
Sample Answer
The short answer
A right shift moves every bit toward the low end. The two flavours differ only in what enters at the top. A logical right shift always shifts in zeros, so it treats the value as an unsigned bit pattern. An arithmetic right shift copies the old top (sign) bit into the vacated positions, so a negative number stays negative. In C, >> on an unsigned type is always logical. On a negative signed value the standard does not say which one you get: the result is implementation-defined (C11 section 6.5.7), meaning each compiler must choose and document it. Almost every mainstream compiler chooses arithmetic, but portable code should not rely on that.
What the standard guarantees
| Expression in C | Guarantee |
|---|---|
u >> n, u unsigned, 0 <= n < width | Defined: floor of u / 2^n, zeros enter at the top |
s >> n, s signed and s >= 0 | Defined: floor of s / 2^n |
s >> n, s signed and s < 0 | Implementation-defined result (not undefined, but not portable) |
any >> or << with n < 0 or n >= width | Undefined behaviour |
s << n for negative s | Undefined behaviour |
Three terms in the table, in plain words. Undefined behaviour means the standard puts no requirement on what the program does at all, so the compiler may produce any result and may assume it never happens. Implementation-defined means the compiler must pick one behaviour and document it, so the result is reliable on one compiler but may differ on another. Two's complement, the way mainstream machines store signed integers, writes a negative number as a bit pattern whose top bit is 1; in that scheme ~x == -x - 1.
So the portable design is to decide which shift you mean and write it so the answer does not depend on the compiler.
Portable versions
- Logical shift of a signed value: convert to unsigned first. Conversion of a signed value to an unsigned type is defined (it wraps modulo 2^32), and shifting an unsigned value is defined:
(uint32_t)x >> n. - Arithmetic shift without relying on the compiler: for a negative
x,~xis non-negative (~x == -x - 1), so shifting it is fully defined. Shift that, then flip back:~(~x >> n). For non-negativexa plain>>is already arithmetic.
Why ~(~x >> n) works, on 8 bits
Take x = -20. In 8 bits (two's complement) that is 11101100. Shifting it directly is the problem case, so complement first:
| step | 8-bit pattern | value |
|---|---|---|
x | 11101100 | -20 |
~x (flip every bit; top bit is now 0, so non-negative) | 00010011 | 19 |
~x >> 2 (defined: zeros enter at the top) | 00000100 | 4 |
~(~x >> 2) (flip back) | 11111011 | -5 |
The result 11111011 is x shifted right by 2 with ones, not zeros, entering at the top. That is exactly what an arithmetic shift does: it sign-extends, meaning it copies the sign bit into the vacated positions. The flip works because complementing turns "fill with copies of the sign bit" into "fill with zeros", which an ordinary shift on a non-negative value already does. The C program below does the same on 32 bits.
Floor and truncation, with one number: -5 / 2 is -2.5. Floor rounds toward minus infinity and gives -3, which is what the arithmetic shift -5 >> 1 gives (11111011 shifted becomes 11111101, which is -3). Truncation rounds toward zero and gives -2, which is what C's / gives for -5 / 2 (C99 and later define this). The two agree for non-negative numbers and for exact divisions, and differ for inexact negative ones.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* Logical right shift: zeros enter on the left. n must be 0..31. */
static uint32_t shr_logical(int32_t x, unsigned n) {
return (uint32_t)x >> n;
}
/* Arithmetic right shift: the sign bit is copied in. n must be 0..31.
For negative x, ~x is non-negative, so the shift below is fully defined. */
static int32_t shr_arithmetic(int32_t x, unsigned n) {
return x < 0 ? ~(~x >> n) : x >> n;
}
int main(void) {
int32_t x = -20;
printf("x = %d = 0x%08x\n", x, (uint32_t)x);
for (unsigned n = 1; n <= 3; n++) {
printf("n=%u logical=0x%08x arithmetic=%d (0x%08x)\n", n,
shr_logical(x, n), shr_arithmetic(x, n),
(uint32_t)shr_arithmetic(x, n));
}
printf("-20 / 8 in C (truncates toward zero) = %d\n", x / 8);
printf("-1 >> 5 arithmetic = %d\n", shr_arithmetic(-1, 5));
printf("-1 >> 5 logical = 0x%08x\n", shr_logical(-1, 5));
printf("INT32_MIN >> 31 arithmetic = %d\n", shr_arithmetic(INT32_MIN, 31));
/* Check against the compiler's own >> (arithmetic on gcc) on many values. */
srand(12345);
for (int i = 0; i < 200000; i++) {
int32_t v = (int32_t)(((uint32_t)rand() << 16) ^ (uint32_t)rand());
unsigned n = (unsigned)(rand() % 32);
if (shr_arithmetic(v, n) != (v >> n)) { printf("MISMATCH\n"); return 1; }
if (v >= 0 && shr_logical(v, n) != (uint32_t)(v >> n)) { printf("MISMATCH\n"); return 1; }
}
printf("portable shifts agree with gcc's >> on 200000 samples\n");
return 0;
}
Output:
x = -20 = 0xffffffec
n=1 logical=0x7ffffff6 arithmetic=-10 (0xfffffff6)
n=2 logical=0x3ffffffb arithmetic=-5 (0xfffffffb)
n=3 logical=0x1ffffffd arithmetic=-3 (0xfffffffd)
-20 / 8 in C (truncates toward zero) = -2
-1 >> 5 arithmetic = -1
-1 >> 5 logical = 0x07ffffff
INT32_MIN >> 31 arithmetic = -1
portable shifts agree with gcc's >> on 200000 samples
Reading the output
-20is0xffffffec. Logically shifted right by 1 it becomes0x7ffffff6, a huge positive number, because a zero entered at the top. Arithmetically shifted it becomes-10(0xfffffff6), which is the sign-preserving answer.- Shifting by 3 gives
-3, not-2: an arithmetic right shift rounds toward negative infinity (floor), so-20 / 8 = -2.5becomes-3. C division truncates toward zero and gives-2for-20 / 8. Using>>as a divide-by-power-of-two on signed values is therefore not the same as/when the value is negative and not exactly divisible. -1shifted arithmetically stays-1for any count (all ones, copy a one in), while the logical shift of the same pattern gives0x07ffffff.- The sanity run compares
shr_arithmeticwith gcc's own>>on 200000 random values and shift counts and finds no mismatch, and the unsigned conversion path agrees with>>on every non-negative sample.
Edge cases and mistakes
- Shift count out of range.
shr_arithmetic(x, 32)would shift by the width, which is undefined. Checkn < 32or mask it (n & 31) and document which. INT32_MIN.~INT32_MINisINT32_MAX, which is representable, so the trick works. Writing-xinstead would overflow, which is why the code uses~.- Assuming
>>divides. It floors,/truncates, and the two disagree for negatives. - Assuming
charis signed. Plaincharmay be signed or unsigned depending on the platform, and right-shifting a promoted negativechar(C first widens it toint, keeping its sign) hits the same implementation-defined rule. Useuint8_twhen you mean bytes. - Java and others. Java defines both shifts (
>>arithmetic,>>>logical), so this question only bites in C and C++.
Running the code
gcc -std=c11 -Wall -Wextra -fsanitize=undefined shift.c -o shift && ./shift
Implement popcount for a 32-bit value in C with no builtins and no large lookup tables, using a fixed number of operations independent of the input. Explain each step on a small example.
Sample Answer
Short answer
Popcount (population count) is the number of 1 bits in a word. The fixed-operation way to compute it is SWAR, short for SIMD within a register (SIMD means one instruction working on many pieces of data at once; here the pieces are small bit-fields packed inside one ordinary 32-bit word, which is why the output below is labelled swar=). It counts in parallel inside the word: first make every 2-bit field hold the number of ones it had, then add neighbouring fields to get 4-bit counts, then 8-bit counts, and finally add the four byte counts with one multiplication. That is 12 operations for any input, with no branches, no loops and no tables, so the amount of work does not depend on the data.
Brute force and why it is not enough
The obvious loop tests all 32 bits (count += (x >> i) & 1). Kernighan's loop (the usual name for the loop that clears the lowest set bit each pass) is better, because x &= x - 1 clears the lowest set bit each time, so it repeats exactly popcount times. But that makes the running time depend on the data, and the loop test is a branch (a point where the processor chooses between two paths of code) whose outcome depends on the input. The question asks for a fixed number of operations and, in the constant-time variant, for no data-dependent branches or loop counts, so both loops are out.
The four steps
- Pairs. A 2-bit field with bits
abhas value 2a + b, and the count of ones is a + b. Subtractinga(the high bit shifted down) gives it:x - ((x >> 1) & 0x55555555). The mask0x55555555selects the high-bit contribution of every pair after the shift. Each field now holds 0, 1 or 2. All four pair values, worked out:
pair ab | value 2a + b | high bit a | value minus a | pair now reads |
|---|---|---|---|---|
00 | 0 | 0 | 0 | 00 (zero ones) |
01 | 1 | 0 | 1 | 01 (one one) |
10 | 2 | 1 | 1 | 01 (one one) |
11 | 3 | 1 | 2 | 10 (two ones) |
The mask matters because x >> 1 also moves the low bit of the pair above into the high slot of this one; ANDing with 0x55555555 (binary 0101...) keeps only the bit that came from the same pair's high position and drops the rest.
2. Nibbles (4-bit fields). Add each pair-count to its neighbour: (x & 0x33333333) + ((x >> 2) & 0x33333333). The masks stop one pair from spilling into the next. Each 4-bit field now holds 0 to 4. Example for one nibble holding two pair-counts 10 10 (two ones and two ones): 1010 & 0011 = 0010 takes the low pair, (1010 >> 2) & 0011 = 0010 takes the high pair moved down, and the sum is 0100, which is 4. Without the masks the unwanted bits of the neighbouring nibble would be added in as well.
3. Bytes. (x + (x >> 4)) & 0x0F0F0F0F. The sum of two nibble counts is at most 8, which fits in 4 bits, so the add can happen before the mask. Each byte now holds 0 to 8.
4. Sum the bytes. Multiplying by 0x01010101 adds copies of the value shifted by 0, 8, 16 and 24 bits, so the top byte of the product is the sum of all four byte counts. The total is at most 32, far below 256, so no byte overflows into its neighbour. Shifting right by 24 extracts it. Unsigned multiplication wraps modulo 2^32 in C, which discards the unwanted upper partial sums without undefined behaviour.
Code (C)
#include <stdint.h>
#include <stdio.h>
/* Fixed sequence of 12 operations, no branches, no loops, no tables. */
static uint32_t popcount32(uint32_t x, FILE *trace) {
/* 1. Each 2-bit field becomes the count of ones it held (0, 1 or 2). */
x = x - ((x >> 1) & 0x55555555u);
if (trace) fprintf(trace, " 2-bit fields : 0x%08X\n", x);
/* 2. Add neighbouring 2-bit counts into 4-bit fields (each now 0..4). */
x = (x & 0x33333333u) + ((x >> 2) & 0x33333333u);
if (trace) fprintf(trace, " 4-bit fields : 0x%08X\n", x);
/* 3. Add neighbouring 4-bit counts into 8-bit fields (each now 0..8). */
x = (x + (x >> 4)) & 0x0F0F0F0Fu;
if (trace) fprintf(trace, " 8-bit fields : 0x%08X\n", x);
/* 4. Multiplying by 0x01010101 sums all four bytes into the top byte. */
x = x * 0x01010101u; /* unsigned multiply wraps modulo 2^32: defined */
if (trace) fprintf(trace, " after multiply: 0x%08X\n", x);
return x >> 24;
}
/* Kernighan's loop for comparison: x & (x - 1) clears the lowest set bit, so the loop runs popcount times. */
static uint32_t popcount_loop(uint32_t x, unsigned *iterations) {
uint32_t count = 0;
while (x != 0) {
x &= x - 1;
count++;
(*iterations)++;
}
return count;
}
int main(void) {
uint32_t samples[] = {0u, 1u, 0xFFFFFFFFu, 0x80000000u, 0x0F0F0F0Fu, 0xF0F0A5C3u};
for (unsigned i = 0; i < sizeof samples / sizeof samples[0]; i++) {
unsigned loop_iterations = 0;
uint32_t loop_result = popcount_loop(samples[i], &loop_iterations);
printf("x=0x%08X swar=%2u loop=%2u (%2u iterations)\n", samples[i],
popcount32(samples[i], NULL), loop_result, loop_iterations);
}
printf("\ntrace for x=0xF0F0A5C3 (binary 1111 0000 1111 0000 1010 0101 1100 0011):\n");
printf(" input : 0xF0F0A5C3\n");
uint32_t result = popcount32(0xF0F0A5C3u, stdout);
printf(" top byte : %u\n", result);
/* Compare with GCC's builtin on edge values and a pinned pseudo-random sequence. */
long bad = 0;
for (int k = 0; k < 32; k++) {
uint32_t p = (uint32_t)1 << k;
uint32_t probes[] = {p, p - 1, ~p, ~(p - 1)};
for (int j = 0; j < 4; j++) if (popcount32(probes[j], NULL) != (uint32_t)__builtin_popcount(probes[j])) bad++;
}
uint32_t state = 5u;
for (int n = 0; n < 2000000; n++) {
state = state * 1664525u + 1013904223u;
if (popcount32(state, NULL) != (uint32_t)__builtin_popcount(state)) bad++;
}
printf("\nmismatches against __builtin_popcount: %ld\n", bad);
return 0;
}
Compiled with gcc 14.2 and -Wall -Wextra -fsanitize=undefined, it prints:
x=0x00000000 swar= 0 loop= 0 ( 0 iterations)
x=0x00000001 swar= 1 loop= 1 ( 1 iterations)
x=0xFFFFFFFF swar=32 loop=32 (32 iterations)
x=0x80000000 swar= 1 loop= 1 ( 1 iterations)
x=0x0F0F0F0F swar=16 loop=16 (16 iterations)
x=0xF0F0A5C3 swar=16 loop=16 (16 iterations)
trace for x=0xF0F0A5C3 (binary 1111 0000 1111 0000 1010 0101 1100 0011):
input : 0xF0F0A5C3
2-bit fields : 0xA0A05582
4-bit fields : 0x40402222
8-bit fields : 0x04040404
after multiply: 0x100C0804
top byte : 16
mismatches against __builtin_popcount: 0
Worked trace: x = 0xF0F0A5C3
The trace above comes from the shipped function. Follow the top byte F0 (1111 0000) through it:
- Pairs:
11 11 00 00become10 10 00 00, because each11holds two ones. That is0xA0, the top byte of the first trace line. - Nibbles: the pair counts
10 10add to 4 (0100) and00 00add to 0, so the byte is0100 0000=0x40. - Bytes: adding the high nibble (4) to the low nibble (0) puts 4 in the low nibble, and the mask clears the high nibble, giving
0x04.
The other bytes work the same way: F0, F0, A5 and C3 each contain four ones, so the byte-count word is 0x04040404. The multiplication 0x04040404 * 0x01010101 wraps to 0x100C0804, whose top byte is 0x10 = 16. A check by digit: F, 0, F, 0, A, 5, C, 3 contain 4 + 0 + 4 + 0 + 2 + 2 + 2 + 2 = 16 ones.
The multiplication laid out in byte columns. Write the byte-count word as bytes b3 b2 b1 b0 = 04 04 04 04. Multiplying by 0x01010101 = 1 + 2^8 + 2^16 + 2^24 adds four copies of the word, shifted left by 0, 8, 16 and 24 bits. Column by column (lowest byte first), each result byte adds the copies that reach it:
| result byte | which input bytes land there | sum |
|---|---|---|
| byte 0 | b0 | 4 = 0x04 |
| byte 1 | b1 + b0 | 8 = 0x08 |
| byte 2 | b2 + b1 + b0 | 12 = 0x0C |
| byte 3 | b3 + b2 + b1 + b0 | 16 = 0x10 |
Read from the top, that is 0x100C0804, the value printed. Copies pushed past byte 3 are lost (the product wraps modulo 2^32), and no column exceeds 32, so no sum carries into the next byte.
Complexity and the constant-time requirement
Time is a fixed 12 operations (4 shifts, 4 ANDs, 3 adds or subtractions and 1 multiply) for every 32-bit input: O(1) with no dependence on the data, and O(1) space (no table). There is no branch and no loop, so no branch or loop count depends on the input. That matters for constant-time code, meaning code whose running time does not vary with its input: if the time depended on a secret value (a key, say), an attacker who measures the time can learn about the secret, a timing attack. Whether the multiply itself takes the same time for every operand is a property of the processor, not of the C language; many cores have a fixed multiply latency, but check your target. For a secret-dependent use, replace the multiply with x += x >> 8; x += x >> 16; return x & 0x3F;, which uses only shifts and adds and gives the same result.
Edge cases and common mistakes
- 0 gives 0 and
0xFFFFFFFFgives 32 (see the sample rows). Neither needs special handling. - Skipping the masks in step 2 or 3 lets one field's count carry into its neighbour and corrupts the result.
- Using signed
int: right shifts of negative values and the final multiply overflow become undefined or implementation-defined; keep every operanduint32_t. - Forgetting the final shift and returning the whole product.
- The result was checked against
__builtin_popcounton powers of two and neighbours, and on 2,000,000 pinned pseudo-random values; the printed mismatch count is 0.
Running the code
gcc -std=c11 -O2 -Wall -Wextra -fsanitize=undefined popcount32.c -o popcount32 && ./popcount32
Save the listing as popcount32.c.
Reverse the bits of a 32-bit unsigned integer. First do it simply, then in O(log W) steps with masks and shifts. How would you make it fast if it is called millions of times?
Sample Answer
The idea in plain words
Reversing a 32-bit word means the bit at position i (position 0 is the least significant bit) must end up at position 31 - i. A mask is a constant whose set bits pick out some positions of another value with &. The fast method uses masks to swap whole groups of bits at once instead of moving bits one at a time.
Simple version: O(W) steps
Take the lowest bit of x, push it onto the bottom of result (shifting what is already there up one place), then drop it from x. After 32 rounds the first bit taken has been shifted all the way to the top. With word width W = 32 this is 32 iterations, each a few operations. On the 8-bit value 00101100 the printed trace shows result growing from the bottom: after round 3 it is 00000001 (the first 1 pushed in), after round 6 00001101, and after round 8 00110100, the input read backwards.
O(log W) version: swap blocks with masks
Reversing a word is the same as doing five swaps, one per power of two. The reason it works: reversing a word means reversing the order of its two halves and also reversing the bits inside each half. Swapping neighbouring blocks of size s reverses the order of the blocks, and the earlier, smaller swaps have already reversed the bits inside each block. So after the 1-bit swap every pair is reversed, after the 2-bit swap every group of four is reversed (two reversed pairs traded places), and so on until the 16-bit swap reverses all 32. The five swaps are:
- swap every pair of neighbouring 1-bit blocks,
- swap every pair of neighbouring 2-bit blocks,
- then 4-bit blocks (nibbles),
- then 8-bit blocks (bytes),
- then the two 16-bit halves.
Each swap is ((x >> s) & m) | ((x & m) << s), where m selects the lower block of every pair (0x55555555 is 0101...01, 0x33333333 is 0011...0011, and so on) and s is the block size. log2(32) = 5 swaps replace 32 loop iterations.
The masks pick the lower block of each pair. For the 1-bit swap, 0x55555555 is 0101...01, so x & m keeps the even-position bits (the lower bit of every pair of neighbours) and (x >> 1) & m brings the upper bit of every pair down to that even position. On 8 bits with x = 00101100 the program prints (x>>1)&mask = 00010100 and (x&mask)<<1 = 00001000, which OR together to 00011100: the pairs 00 10 11 00 became 00 01 11 00, each pair reversed. The next swap with 0x33 (00110011) gives 01000011, where the groups of four are reversed in order, and the swap with 0x0F gives 00110100, the full 8-bit reversal.
Fast when called millions of times: a lookup table
Build a 256-entry table holding the reversal of every possible byte once (256 bytes of memory). Reversing a word is then four table lookups: reverse each byte through the table and place the reversed bytes in opposite order. There are no data-dependent branches (jumps whose direction depends on the data, which the CPU can mispredict), and the table is small enough to stay in the data cache (the small fast memory inside the CPU that holds recently used data). A 65,536-entry table for 16-bit halves needs only two lookups but takes 65,536 * 2 bytes = 131,072 bytes = 128 KiB with 2-byte entries, 512 times the 256-byte table, which is bigger than the data cache of many cores, so the extra misses can cancel the saving. Pick between them by measuring on the real target.
Two further options apply to particular targets and tasks. On AArch64 (64-bit Arm) a single RBIT instruction reverses a register's bits (reachable through the compiler's intrinsics, functions that map directly to one machine instruction, or through inline assembly), so check what your target offers before writing tables. And if the real goal is a bit-reversal permutation, the reordering of an array by bit-reversed index that an FFT (fast Fourier transform) needs, a recurrence that builds the whole index table in O(n) avoids per-call work altogether.
Code (C, uint32_t)
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* Simple: peel bits off the bottom of x and push them onto the bottom of result. */
uint32_t reverse_loop(uint32_t x) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (x & 1u);
x >>= 1;
}
return result;
}
/* One swap step: exchange neighbouring blocks of `shift` bits. */
static const uint32_t MASKS[5] = {0x55555555u, 0x33333333u, 0x0F0F0F0Fu,
0x00FF00FFu, 0x0000FFFFu};
static const unsigned SHIFTS[5] = {1, 2, 4, 8, 16};
uint32_t swap_step(uint32_t x, int step) {
uint32_t m = MASKS[step];
unsigned s = SHIFTS[step];
return ((x >> s) & m) | ((x & m) << s);
}
/* O(log W) steps: log2(32) = 5 block swaps. */
uint32_t reverse_masks(uint32_t x) {
for (int step = 0; step < 5; step++)
x = swap_step(x, step);
return x;
}
/* Fast for many calls: one 256-entry table, 4 lookups per word. */
static uint8_t byte_table[256];
void init_byte_table(void) {
for (unsigned b = 0; b < 256; b++)
byte_table[b] = (uint8_t)(reverse_loop(b) >> 24);
}
uint32_t reverse_table(uint32_t x) {
return ((uint32_t)byte_table[x & 0xFFu] << 24) |
((uint32_t)byte_table[(x >> 8) & 0xFFu] << 16) |
((uint32_t)byte_table[(x >> 16) & 0xFFu] << 8) |
(uint32_t)byte_table[x >> 24];
}
static void print8(uint32_t x) {
for (int i = 7; i >= 0; i--) putchar(((x >> i) & 1u) ? '1' : '0');
}
/* The same two ideas on an 8-bit value, so every bit fits on one line. */
static void trace8(uint32_t x) {
printf("8-bit loop on "); print8(x); printf(":\n");
uint32_t result = 0, rest = x;
for (int i = 0; i < 8; i++) {
result = (result << 1) | (rest & 1u);
rest >>= 1;
printf(" round %d: result = ", i + 1); print8(result); printf(" rest = "); print8(rest); printf("\n");
}
printf("8-bit block swaps on "); print8(x); printf(":\n");
uint32_t masks8[3] = {0x55u, 0x33u, 0x0Fu};
unsigned shifts8[3] = {1, 2, 4};
for (int step = 0; step < 3; step++) {
uint32_t m = masks8[step];
unsigned s = shifts8[step];
uint32_t hi = (x >> s) & m, lo = (x & m) << s;
printf(" swap %u: (x>>%u)&mask = ", s, s); print8(hi);
printf(" (x&mask)<<%u = ", s); print8(lo);
x = hi | lo;
printf(" x = "); print8(x); printf("\n");
}
}
int main(void) {
init_byte_table();
trace8(0x2Cu);
uint32_t x = 0x12345678u;
printf("input %08X\n", x);
uint32_t t = x;
for (int step = 0; step < 5; step++) {
t = swap_step(t, step);
printf("after swap %2u %08X\n", SHIFTS[step], t);
}
printf("loop %08X\n", reverse_loop(x));
printf("masks %08X\n", reverse_masks(x));
printf("table %08X\n", reverse_table(x));
srand(12345);
long checked = 0;
for (int i = 0; i < 1000000; i++) {
uint32_t v = ((uint32_t)rand() << 16) ^ (uint32_t)rand() ^ ((uint32_t)rand() << 31);
uint32_t a = reverse_loop(v);
if (a != reverse_masks(v) || a != reverse_table(v) || reverse_masks(a) != v) {
printf("MISMATCH %08X\n", v);
return 1;
}
checked++;
}
uint32_t edges[] = {0u, 1u, 0x80000000u, 0xFFFFFFFFu};
for (int i = 0; i < 4; i++)
printf("edge %08X -> %08X\n", edges[i], reverse_masks(edges[i]));
printf("all three agree on %ld random words\n", checked);
return 0;
}
Output
Run with gcc -std=c11 -Wall -Wextra -fsanitize=undefined (GCC 14.2, aarch64 Linux), it prints:
8-bit loop on 00101100:
round 1: result = 00000000 rest = 00010110
round 2: result = 00000000 rest = 00001011
round 3: result = 00000001 rest = 00000101
round 4: result = 00000011 rest = 00000010
round 5: result = 00000110 rest = 00000001
round 6: result = 00001101 rest = 00000000
round 7: result = 00011010 rest = 00000000
round 8: result = 00110100 rest = 00000000
8-bit block swaps on 00101100:
swap 1: (x>>1)&mask = 00010100 (x&mask)<<1 = 00001000 x = 00011100
swap 2: (x>>2)&mask = 00000011 (x&mask)<<2 = 01000000 x = 01000011
swap 4: (x>>4)&mask = 00000100 (x&mask)<<4 = 00110000 x = 00110100
input 12345678
after swap 1 2138A9B4
after swap 2 84C2A6E1
after swap 4 482C6A1E
after swap 8 2C481E6A
after swap 16 1E6A2C48
loop 1E6A2C48
masks 1E6A2C48
table 1E6A2C48
edge 00000000 -> 00000000
edge 00000001 -> 80000000
edge 80000000 -> 00000001
edge FFFFFFFF -> FFFFFFFF
all three agree on 1000000 random words
The first two blocks of output are the 8-bit traces described above. Each line after input is the real intermediate state of swap_step. For example 12345678 becomes 2138A9B4 after the 1-bit swap: every pair of adjacent bits traded places, so the nibble 0x1 (0001) became 0x2 (0010).
Complexity
| Method | Time per call | Extra space |
|---|---|---|
| loop | 32 iterations, O(W) | O(1) |
| masks | 5 steps, O(log W) | O(1) |
| table | 4 lookups, O(W / 8) | 256 bytes, built once |
All three work on a fixed 32-bit word, so every one is a constant number of operations in absolute terms. The O(W) and O(log W) labels describe how the step count grows with the word width.
Edge cases and common mistakes
0and0xFFFFFFFFmap to themselves;1and0x80000000swap (all in the output).- Use
uint32_t. With a signedint,x >> 1on a negative value is implementation-defined (the compiler must pick a behaviour and document it; GCC copies the sign bit in) and typically drags in sign bits, andx << 1can overflow, which is undefined behaviour (the C standard places no requirement on what the program then does). - Cast table entries to
uint32_tbefore shifting by 24. Auint8_tis promoted to a signedint, and0x80 << 24does not fit inint. - A loop of 31 or 33 iterations gives a result off by one position.
- Reversing bits is not reversing bytes. Byte swapping (for endianness) keeps the bit order inside each byte; it is steps 4 and 5 only.
Running the code
gcc -std=c11 -Wall -Wextra -fsanitize=undefined -o reverse_bits reverse_bits.c && ./reverse_bits
Unlock Full Question Bank
Get access to all 30 Bit Manipulation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.