Bit Manipulation Algorithms
Bitwise operations treat integers as sequences of binary digits. They are useful for masks, compact state representation, low-level algorithms, subsets, hashing, graphics, networking, and performance-sensitive code.
Core Operators
| Operation | Symbol | Example |
|---|---|---|
| AND | & | 5 & 3 = 1 |
| OR | | | 5 | 3 = 7 |
| XOR | ^ | 5 ^ 3 = 6 |
| NOT | ~ | bitwise complement |
| Left shift | << | 5 << 1 = 10 |
| Right shift | >> | 5 >> 1 = 2 |
Bit Masks
To operate on bit position k, create a mask 1 << k.
set: n | (1 << k)
clear: n & ~(1 << k)
toggle: n ^ (1 << k)
test: (n & (1 << k)) != 0These operations are constant-time under the usual fixed-width machine-integer model.
Count Set Bits
A simple method examines every bit. Brian Kernighan's method repeatedly clears the lowest set bit:
count = 0
while n != 0:
n = n & (n - 1)
count++The loop runs once per set bit, so its time is O(number of 1-bits).
Power of Two Test
A positive power of two has exactly one set bit.
isPowerOfTwo(n):
return n > 0 and (n & (n - 1)) == 0For example, 8 = 1000₂ and 7 = 0111₂, so 8 & 7 = 0.
Subset Representation
An n-bit integer can represent a subset of n items: bit i is 1 if item i is included.
for mask = 0 to (1 << n) - 1:
process subset represented by maskThis is common in exhaustive search and bitmask dynamic programming. Enumerating all subsets takes Θ(2ⁿ).
XOR Patterns
XOR has useful identities: x ^ x = 0, x ^ 0 = x, and it is associative and commutative.
This can find a unique value when every other value appears exactly twice.
result = 0
for x in array:
result ^= xThe classic XOR-swap trick exists, but normal temporary-variable swapping is clearer and usually preferable in real code.
Interactive Bit Playground
Where Bit Manipulation Appears
- Flags and permission masks
- Subset enumeration and bitmask DP
- Bloom filters and hashing
- Compression and encoding
- Graphics and image processing
- Networking protocols and packet fields
- Cryptographic primitives