Introduction
A number is a row of bits, and C++ lets you work on them directly. This is fast, since every operation is one instruction, and it is also a compact way to store a set of yes-or-no flags. Contests use bit tricks to shorten code, to cancel pairs with xor, and above all to try every subset of a small set by counting from 0 to 2ⁿ - 1.
How it works
The operators
x & ykeeps the bits set in both (44 & 4is 4).x | ykeeps the bits set in either (44 | 1is 45).x ^ ykeeps the bits that differ (44 ^ 32is 12).~xflips every bit (~44is -45).x << kshifts left, which multiplies by 2 to the power k (1 << 5is 32).x >> kshifts right, which divides by 2 to the power k (44 >> 2is 11).
With them, one bit is easy: (x >> i) & 1 reads bit i, x | (1 << i) sets it, x & ~(1 << i) clears it and x ^ (1 << i) toggles it. Use 1LL << i when i can pass 30, so the shift happens in 64 bits.
Two useful tricks
x & (x - 1) removes the lowest one bit of x. A loop for (y = x; y > 0; y &= y - 1) count++; counts the one bits, taking one step per bit. x & -x isolates the lowest one bit, which is the power of two that divides x most.
XOR has two properties worth remembering: x ^ x = 0 and x ^ 0 = x. If you xor a list of numbers, every number that appears twice cancels, and only a number that appears an odd number of times is left.
Subsets as masks
A set of n items has 2ⁿ subsets. Let bit i of mask say whether item i is in the subset. Then for (mask = 0; mask < (1 << n); mask++) visits every subset exactly once. For n up to about 20 this is fast enough: 2²⁰ is about a million masks.
Precedence. Comparison binds tighter than & in C++, so write (x & 1) == 0, not x & 1 == 0. When in doubt, add parentheses.
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
int x = 44; // binary 101100
cout << "bit 2 of 44: " << ((x >> 2) & 1) << "\n";
cout << "set bit 0: " << (x | 1) << "\n";
cout << "clear bit 2: " << (x & ~(1 << 2)) << "\n";
cout << "toggle bit 5: " << (x ^ (1 << 5)) << "\n";
cout << "lowest set bit: " << (x & -x) << "\n";
int count = 0;
for (int y = x; y > 0; y &= y - 1) count++;
cout << "one bits: " << count << "\n";
string names = "abc";
for (int mask = 0; mask < (1 << 3); mask++) {
cout << mask << ": {";
for (int i = 0; i < 3; i++)
if ((mask >> i) & 1) cout << names[i];
cout << "}\n";
}
return 0;
}The program works on 44, which is 101100 in binary. It reads, sets, clears and toggles bits, finds the lowest one bit, counts the one bits, and then lists the 8 subsets of the letters a, b and c by counting masks from 0 to 7.
Line by line
(x >> 2) & 1shifts bit 2 down to the right-most place and keeps only it.x & ~(1 << 2)builds a mask with every bit set except bit 2, so the&clears it.x & -xis 4 for 44, because the lowest one bit of 101100 is 100.- The
for (y = x; y > 0; y &= y - 1)loop counts 3 one bits. - Inside the mask loop,
(mask >> i) & 1tells whether letteriis in this subset.
Expected result
bit 2 of 44: 1
set bit 0: 45
clear bit 2: 40
toggle bit 5: 12
lowest set bit: 4
one bits: 3
0: {}
1: {a}
2: {b}
3: {ab}
4: {c}
5: {ac}
6: {bc}
7: {abc}
In the real world
Bit masks appear in file permissions (read, write, execute), network masks and flags in system calls. Graphics code packs colours into bits, hash functions mix bits, and checksum and error-correcting codes rely on xor. Dynamic programming over subsets, which solves small travelling-salesman and assignment problems, stores its states as masks.
Common mistakes
- Using
1 << iforiof 31 or more, which overflows anint; write1LL << i. - Forgetting parentheses:
x & 1 == 0does not mean what it seems to. - Using
>>on a negative number and expecting a pure bit shift. - Looping over
2^nmasks with n above about 25, which is too slow. - Mixing up
&(bits) with&&(logic).
Best practices
- Name your masks and write the operation in a comment.
- Use
1LL <<when a shift can reach 31 or more. - Prefer
x & (x - 1)loops over scanning all 64 bits when few bits are set. - Keep n at 20 or below when you enumerate subsets.
- Add parentheses around every bit operation inside a larger expression.
Summary
Bits let you read and change flags in one instruction. x & (x - 1) and x & -x work on the lowest one bit, xor cancels numbers that come in pairs, and a mask from 0 to 2ⁿ - 1 walks through every subset of n items.
Quick check
Key takeaways
- (x >> i) & 1 reads bit i, and x | (1 << i) sets it
- x & (x - 1) removes the lowest one bit, so a loop of it counts the bits
- x ^ x = 0 and x ^ 0 = x, so xor cancels numbers that appear twice
- A set of n items has 2ⁿ subsets, each one an integer from 0 to 2ⁿ - 1
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.