Overview
Curated: · Written: · Reviewed:
Bit Manipulation
In one line
Working on an integer's binary digits with AND, OR, XOR, NOT and shifts, inside a fixed width, to test, set, clear or isolate bits, enumerate subsets, or pack fields in constant time. Reach for it when bits are the domain model (flags, protocol fields, sets over a universe no wider than the word) or when an identity such as x & (x - 1) gives the answer directly. It is not a general speed-up.
Key definitions
- Two's complement: signed encoding where the top bit has weight -2^(w-1).
-xequals~x + 1. - Arithmetic vs logical shift:
>>on a signed value replicates the sign bit and rounds toward negative infinity. Unsigned types, and Java's>>>, fill with zeros. - Lowest set bit:
x & -x. Clear it withx & (x - 1). - Submask:
sis a submask ofmwhens & m == s. Enumerate withsub = (sub - 1) & m. - Width: the bit count the type guarantees. Shifts at or above it are undefined in C, masked to the low 5 bits in Java, and unbounded in Python.
Formulas and complexity
- Kernighan popcount: O(number of set bits), not O(width).
- Iterate set bits with isolate and clear: one step per set bit.
- XOR pairing: O(n) time, O(1) extra space.
How it works
- An integer of width w is a vector of w booleans. Test with
x & (1 << i)and compare to zero. Set with|=, clear with&= ~(1 << i), toggle with^=. - Subtracting one flips the trailing zeros and the lowest set bit, so
x & (x - 1)clears exactly the lowest set bit. Example:0b10110100 & -0b10110100is0b100. x ^ x = 0andx ^ 0 = x, so a XOR over a list that pairs every value cancels the pairs and leaves the unpaired one.- With two unpaired values p and q,
x = p ^ qis nonzero. Any set bit of x separates p from q, so XOR each group to recover them.
When to use and when not to
| Situation | Use bits | Use something else |
|---|---|---|
| Flags, permissions, feature sets | yes | |
| Dense set over a universe of at most 64 elements | yes, union and intersection in one instruction | bitset library or hash set beyond the word |
| Dense membership over 10,000,000 ids | bitset, 1.25 MB | hash set when sparse |
| Subset DP | up to about n = 20 | larger n: 2^n x n table outgrows memory |
Replacing n // 2 with n >> 1 | no | compiler already emits the shift for unsigned values; differs for negatives |
| Packing a network field | yes | explicit byte order at the boundary |
Traps interviewers probe
- Dividing a signed value with a shift.
-25 >> 3is -4, while-25 / 8truncates to -3. Fix: use division when the rounding direction matters. - Shift counts at the width. Java
7 << 32is 7 because the count is masked to 0, so(shardId << 32) | sequencedrops the shard. Fix: widen to long before shifting, and keep counts below the width. - Toggling where you mean to set or clear.
state ^= 1 << 5flips the bit, so resuming an unpaused job pauses it. Fix:state &= ~(1 << 5)to clear,|=to set. - Renumbering flags with auto(). Inserting a member between existing ones shifts the values after it, so a stored 8 changes meaning. Fix: assign explicit powers of two and append new members.
- Overflow checks after the fact. In C the compiler may delete a check such as
a + b < a. Fix: testb > 0 && a > INT_MAX - bbefore the addition.
Interview tips
Open by naming the type and its width and signedness, then the identity you rely on, such as two's complement negation or XOR self-cancellation.
Expect these follow-ups: what changes past 64 elements; what breaks for negative inputs and for n = 0; why the loop is O(set bits); what changes when an element appears three times; why the XOR swap fails when both operands alias.
30-second outline: Represent the set as a mask over N items. Each step isolates the lowest set bit with x & -x, processes it, and clears it with x &= x - 1, so cost follows the number of set bits, not the width. Submasks come from sub = (sub - 1) & m, which visits each subset once; summed over all masks that is 3^n. I would state the width, check the sign before shifting, and use a bitset only while the universe fits the word.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.