Bit Manipulation
Working on the binary digits of integers with AND, OR, XOR, NOT and shifts: single-bit recipes, XOR cancellation, bit counting and bitmask subsets.
Overview
Bit manipulation means working on the binary digits (bits) of an integer directly, with the bitwise operators. It tests whether you can think in binary: a handful of identities turn problems that look like they need a hash map or extra memory into O(1) space loops.
Bits are numbered from the right, starting at 0. Bit i is worth 2 to the power i, so 22 is 10110: bits 1, 2 and 4 are set (2 + 4 + 16).
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
The six operators
The rule: each operator works on every bit position independently, except the shifts, which move bits. The examples use 5 (101) and 3 (011).
- AND (&) gives 1 only where both bits are 1. 5 & 3 compares 101 with 011 and gives 001, which is 1.
- OR (|) gives 1 where either bit is 1. 5 | 3 is 111, which is 7.
- XOR (^) gives 1 where the bits differ. 5 ^ 3 is 110, which is 6.
- NOT (~) flips every bit. ~5 is -6, since ~x = -(x+1).
- Left shift (>) moves bits right. 20 >> 2 is 101, which is 5.
A left shift by n multiplies by 2 to the power n, and a right shift by n is floor division by 2 to the power n.
> [!WARNING] > Because the right shift floors, -7 >> 1 is -4, not -3.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio