Bit tricks and subset masks

Intermediate

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 & y keeps the bits set in both (44 & 4 is 4).
  • x | y keeps the bits set in either (44 | 1 is 45).
  • x ^ y keeps the bits that differ (44 ^ 32 is 12).
  • ~x flips every bit (~44 is -45).
  • x << k shifts left, which multiplies by 2 to the power k (1 << 5 is 32).
  • x >> k shifts right, which divides by 2 to the power k (44 >> 2 is 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;
}
Open in compiler

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) & 1 shifts 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 & -x is 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) & 1 tells whether letter i is 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 << i for i of 31 or more, which overflows an int; write 1LL << i.
  • Forgetting parentheses: x & 1 == 0 does not mean what it seems to.
  • Using >> on a negative number and expecting a pure bit shift.
  • Looping over 2^n masks 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

1. What does x & (x - 1) do?
2. What is 5 ^ 5 ^ 9?
3. How many subsets does a set of 10 items have?
4. Which expression sets bit i of x?

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.