Bit Manipulation
Basic operations of bit manipulation
Bit Manipulation
1. Basics
- Integers are stored as binary. Bit positions are counted from the right, starting at 0 (the least significant bit, LSB).
inthas 32 bits,long longhas 64. - Bit operators work directly on the stored bits, so no decimal/binary conversion is needed in code. To print bits:
cout << bitset<8>(6);gives00000110. - Two's complement (how negatives work):
-x = ~x + 1.-1is all 1s. The top bit (bit 31) is the sign bit. - Prefer
unsignedtypes for pure bit work, to avoid sign-related surprises.
2. Bitwise Operators
| Op | Name | Rule | Example (6 = 110, 3 = 011) |
|---|---|---|---|
& |
AND | 1 only if both bits are 1 | 6 & 3 = 010 |
| |
OR | 1 if either bit is 1 | 6 | 3 = 111 |
^ |
XOR | 1 if the bits differ | 6 ^ 3 = 101 |
~ |
NOT | flips every bit | ~6 = ...11111001 (-7) |
>> |
Right shift | moves bits right | 6 >> 1 = 011 |
<< |
Left shift | moves bits left | 6 << 1 = 1100 |
Right Shift
x >> b shifts every bit b places to the right. Bits that fall off the right end are discarded.
x = 6 = 110
6 >> 0 = 110
6 >> 1 = 011
6 >> 2 = 001
- After shifting right by
b, the bit that was at positionbis now in the rightmost spot. - For non-negative x,
x >> bequalsx / 2^b. - On negative signed ints,
>>is an arithmetic shift in practice (the sign bit is copied in). Before C++20 this was implementation-defined.
Left Shift
1 << b starts from 1 and shifts it left b places. That gives a number with exactly one bit on, at position b.
1 << 0 = 0001
1 << 1 = 0010
1 << 2 = 0100
1 << 3 = 1000
x << bequalsx * 2^b(if it doesn't overflow).- Use
1LL << bwhenb >= 31. Plain1 << boverflows anint. - Shifting by a negative amount, or by
>=the type's bit width, is undefined behavior.
3. Core Bit Operations (single bit)
| Goal | Code | Idea |
|---|---|---|
Read bit b of x |
(x >> b) & 1 |
shift it to the right edge, then isolate it |
Check bit b is set |
x & (1 << b) |
nonzero means set |
Set bit b |
x |= (1 << b) |
build a one-bit mask, then OR it in |
Clear bit b |
x &= ~(1 << b) |
mask has every bit on except b, then AND |
Toggle bit b |
x ^= (1 << b) |
XOR with the one-bit mask flips just that bit |
Is x odd? |
x & 1 |
the rightmost bit decides |
Lowest k bits mask |
(1 << k) - 1 |
e.g. k=3 gives 0111 |
Extract bits l..r |
(x >> l) & ((1 << (r-l+1)) - 1) |
shift down, then mask the width |
4. Useful Tricks
| Goal | Code | Why it works |
|---|---|---|
| Isolate lowest set bit | x & -x |
-x flips everything above the lowest 1, so only that bit survives |
| Clear lowest set bit | x & (x - 1) |
x-1 flips the lowest 1 and the zeros below it |
| Set lowest unset bit | x | (x + 1) |
x+1 carries through trailing 1s |
| Is power of 2? | x > 0 && (x & (x - 1)) == 0 |
a power of 2 has exactly one set bit |
| Multiply by 2^k | x << k |
|
| Divide by 2^k (x >= 0) | x >> k |
|
x % 2^k (x >= 0) |
x & ((1 << k) - 1) |
keeps the low k bits |
| Swap without temp | a ^= b; b ^= a; a ^= b; |
breaks if a and b are the same variable |
| Opposite signs? | (a ^ b) < 0 |
the sign bits differ |
Add without + |
a + b = (a ^ b) + ((a & b) << 1) |
XOR is the sum without carry, AND shifted is the carry (loop until carry is 0) |
| Hamming distance | popcount(a ^ b) |
XOR marks the differing bits |
| Gray code of i | i ^ (i >> 1) |
|
| Bits needed for n | 32 - __builtin_clz(n) (n > 0) |
5. Counting Set Bits (popcount)
- Built-in (GCC/Clang):
__builtin_popcount(x)forunsigned int,__builtin_popcountll(x)forlong long. - C++20:
std::popcount(x)from<bit>. - Brian Kernighan's algorithm: each
x &= (x - 1)removes the lowest set bit, so the loop runs once per set bit.
int cnt = 0;
while (x) { x &= (x - 1); cnt++; }- Counting bits for all of 0..n (DP):
dp[i] = dp[i >> 1] + (i & 1).
6. Built-in Functions (GCC/Clang)
| Function | Returns |
|---|---|
__builtin_popcount(x) |
number of 1 bits |
__builtin_clz(x) |
count of leading zeros (undefined for x = 0) |
__builtin_ctz(x) |
count of trailing zeros (undefined for x = 0) |
__builtin_parity(x) |
1 if the count of set bits is odd |
(Add ll for long long: __builtin_popcountll, etc.) |
7. XOR Properties
a ^ a = 0a ^ 0 = a- Commutative and associative, so order doesn't matter and pairs cancel anywhere in the array.
a ^ b ^ b = a, so XOR is its own inverse (used in swap, encryption, and finding differences).- XOR of a bit column is 1 when the count of 1s is odd, i.e. it's
count % 2. - Prefix XOR: with
p[i] = a[0] ^ ... ^ a[i], the XOR of range[l, r]isp[r] ^ p[l-1].
8. Bitmask Techniques
- Set as a bitmask: bit
iset means elementiis in the set. Union is|, intersection is&, difference isa & ~b. - Enumerate all subsets of n elements:
for (int mask = 0; mask < (1 << n); mask++)
for (int i = 0; i < n; i++)
if ((mask >> i) & 1) { /* element i is in this subset */ }- Enumerate all submasks of a mask:
for (int s = mask; s > 0; s = (s - 1) & mask) { /* use s */ }- Bitmask DP (e.g. TSP, assignment problems) stores "which items are used so far" as a mask, with
n <= ~20. std::bitset<N>gives a fixed-size bit array with.set(),.reset(),.flip(),.count(),.test().
9. Common Pitfalls
- Precedence:
==binds tighter than&,^,|. Sox & 1 == 0is wrong. Write(x & 1) == 0. When in doubt, add parentheses. - Overflow: use
1LL << bforb >= 31. NegatingINT_MINoverflows, so uselong longbeforex & -x. - Shift amount: shifting by
>=the bit width, or by a negative amount, is undefined behavior. - Signed shifts: left-shifting into the sign bit and right-shifting negatives behave differently across standards. Use
unsignedwhen you can. ~xon small types is promoted tointfirst, which can surprise you with the upper bits.- Swap-by-XOR zeroes the value if both operands are the same memory location.
- Loop bugs like
i + 2instead ofi += 2silently do nothing (a-Wallwarning will catch it).
10. Single Number Family (patterns)
- Single Number (I): every number appears twice except one. XOR everything, pairs cancel, the single is left. O(n) time, O(1) space.
- Single Number II: every number appears 3 times except one. For each of the 32 bit positions, count the 1s across all numbers. The tripled numbers add a multiple of 3, so
count % 3is the single number's bit. Rebuild the answer withans |= (1 << b). (Single Number I is the same idea with% 2.) - Single Number III: two singles
aandb. XOR everything to getx = a ^ b. Take the lowest set bitmask = x & -x, a bit whereaandbdiffer. Split the numbers byn & mask, then XOR each group to getaandb. Uselong longforxto avoid overflow when negatingINT_MIN. - XOR of numbers that appear twice: plain XOR won't work, because it cancels the pairs you want. Track what's been seen (a
boolarray or a bitmask with(mask >> x) & 1andmask |= 1LL << x) and XOR a number into the answer on its second occurrence. - Missing Number: XOR all of
0..nwith all array elements. Everything cancels except the missing number.
11. Problems
Solved:
To practice:
Backlinks
Nothing links here yet. Notes link by filename, so this fills in as the corpus grows.