Bit manipulation
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Bit manipulation works directly with the on/off switches (bits) inside a number to store many yes/no facts in one value or to do clever tricks quickly. It is compact and very fast, and shows up in permissions, flags and checks.
Practical use cases
- Web app: Storing user permissions in one number. An admin panel gives users any combination of read, write, delete and publish rights. Instead of four database columns, one number holds all four as bits, and checking a permission is a quick bitwise AND. One small number holds every right, the database row is smaller, and a check is a single quick operation.
- Web app: Finding the one lonely ticket. A ticketing system has pairs of duplicate scan records plus one unmatched entry. XOR-ing all the numbers cancels every pair, leaving only the unmatched ticket, with no sorting and no lookup table.
- Web app: Feature flags and filter combinations. A shop with 20 on/off filters stores a user's chosen set as a single integer. It fits into a short URL or cache key, and two selections can be compared in one step.
- System: Encryption, hashing and error detection. Hash functions, encryption and checksums are built from XOR, shifts and masks, and games use bit boards to represent boards and subsets compactly. The same tiny operations make hashing and checksums fast, and let game boards fit into a single number.
The story: The Lonely Ticket
After the school fair, Kabir found a heap of raffle ticket stubs. Every ticket number had been torn into two matching halves and one stub had lost its twin. "Which number has no partner?" Mrs. Sharma wanted to know. Kabir started a notebook: write each number, tick when the partner shows up. With a million stubs, his notebook would be bigger than the school.
Mira had been learning how computers store numbers: as little switches that are on or off (bits). She showed Kabir a special mixing game called XOR: when you mix two switch rows, a switch is ON only if the two were different. Mixing a number with itself turns every switch OFF: it vanishes. And mixing with nothing changes nothing.
"So mix all the stubs into one running number," she said. Every pair cancels itself, whatever the order, and only the lonely number survives. No notebook, one number of memory.
That is bit manipulation. The smell: "appears twice except one", "without extra space", "power of two", "count the 1 bits", "all subsets of a small set (use bit masks)", "toggle / flip flags". When numbers are only on/off switches inside, bitwise tricks can replace loops and notebooks.
How to spot this problem, and where you need it
You are storing or comparing many small yes/no facts, or hunting for the odd one out among pairs, and using lots of columns, arrays or loops feels heavy.
Signs you need it
- You have several boolean flags that are always saved or checked together, such as roles, features or options.
- The problem says every item appears twice except one, or asks for all subsets of a small set.
- You need very compact data, such as in cache keys, URLs or big arrays of flags.
Where to use it in a project
- Role and permission systems where each user holds a combination of rights.
- Feature flags and filter selections saved in URLs, cookies or cache keys.
- Checksums, hashing and puzzle or subset enumeration code.
The solution
Give each fact its own bit position (read = 1, write = 2, delete = 4, publish = 8). Combine facts with OR, check one with AND, turn one off with AND NOT, and flip with XOR. For the lonely item, XOR everything together: equal numbers cancel to zero, and the one left over is the answer. For subsets, count from 0 up to the total and read each number as a pattern of on-off bits.
Payoff: Before: four columns and four checks per user. After: one number and one quick check.
Explain it like I am 8
Think of a row of light switches. XOR flips the light only where the second row also says "flip". If you flip the same pattern twice, every light is back to where it began. So when pairs of the same pattern are applied, they undo each other, and only the pattern with no twin remains.
How it works, step by step
- Spot the clue: numbers that pair up, "no extra memory", powers of two, flags or subsets of a small set.
- Learn the four tools:
&(both on),|(either on),^XOR (different),<</>>shift. - XOR facts:
x ^ x = 0,x ^ 0 = x, and order does not matter. So XOR of a list with every value doubled except one gives that one. - Useful one-liners:
n & (n - 1)erases the lowest ON switch (count bits, test for power of two);(n >> i) & 1reads switch i. - Loop once:
result ^= xfor every item and returnresult.
The code in four languages
PHP
<?php
// Classic 1: "Single Number": everything appears twice except one.
function singleNumber(array $nums): int {
$result = 0;
foreach ($nums as $x) {
$result ^= $x; // pairs cancel (x ^ x = 0), the lonely one survives
}
return $result;
}
echo singleNumber([4, 1, 2, 1, 2]), "
"; // 4
// Classic 2: count the 1 bits. n & (n - 1) switches off the lowest ON bit.
function countBits(int $n): int {
$count = 0;
while ($n > 0) {
$n &= $n - 1; // one ON bit removed per loop
$count++;
}
return $count;
}
echo countBits(13), " (13 is 1101 in binary)
"; // 3
// Power of two has exactly one ON bit.
function isPowerOfTwo(int $n): bool { return $n > 0 && ($n & ($n - 1)) === 0; }
echo var_export(isPowerOfTwo(16), true), " ", var_export(isPowerOfTwo(18), true); // true falseJavaScript
// Classic 1: "Single Number": everything appears twice except one.
function singleNumber(nums) {
let result = 0;
for (const x of nums) {
result ^= x; // pairs cancel (x ^ x = 0), the lonely one survives
}
return result;
}
console.log(singleNumber([4, 1, 2, 1, 2])); // 4
// Classic 2: count the 1 bits. n & (n - 1) switches off the lowest ON bit.
function countBits(n) {
let count = 0;
while (n > 0) {
n &= n - 1; // one ON bit removed per loop
count++;
}
return count;
}
console.log(countBits(13) + ' (13 is 1101 in binary)'); // 3
// Power of two has exactly one ON bit.
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
console.log(isPowerOfTwo(16), isPowerOfTwo(18)); // true falseJava
public class Main {
// Classic 1: "Single Number": everything appears twice except one.
static int singleNumber(int[] nums) {
int result = 0;
for (int x : nums) {
result ^= x; // pairs cancel (x ^ x = 0), the lonely one survives
}
return result;
}
// Classic 2: count the 1 bits. n & (n - 1) switches off the lowest ON bit.
static int countBits(int n) {
int count = 0;
while (n > 0) {
n &= n - 1; // one ON bit removed per loop
count++;
}
return count;
}
// Power of two has exactly one ON bit.
static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
public static void main(String[] args) {
System.out.println(singleNumber(new int[]{4, 1, 2, 1, 2})); // 4
System.out.println(countBits(13) + " (13 is 1101 in binary)"); // 3
System.out.println(isPowerOfTwo(16) + " " + isPowerOfTwo(18)); // true false
}
}Go
package main
import "fmt"
// singleNumber: everything appears twice except one.
func singleNumber(nums []int) int {
result := 0
for _, x := range nums {
result ^= x // pairs cancel (x ^ x = 0), the lonely one survives
}
return result
}
// countBits counts the 1 bits. n & (n - 1) switches off the lowest ON bit.
func countBits(n int) int {
count := 0
for n > 0 {
n &= n - 1 // one ON bit removed per loop
count++
}
return count
}
// isPowerOfTwo: a power of two has exactly one ON bit.
func isPowerOfTwo(n int) bool { return n > 0 && n&(n-1) == 0 }
func main() {
fmt.Println(singleNumber([]int{4, 1, 2, 1, 2})) // 4
fmt.Println(countBits(13), "(13 is 1101 in binary)") // 3
fmt.Println(isPowerOfTwo(16), isPowerOfTwo(18)) // true false
}Time: O(n) · Extra space: O(1). One pass over the list with a single running number; no extra storage.
Watch out for
- Confusing
&and&&, or|and||. Bitwise and logical operators differ. - Using XOR when a value may appear three times or when more than one number is lonely. The cancel-in-pairs trick only works for even counts.
- Forgetting JavaScript bitwise operators work on 32-bit signed integers, so large numbers or negatives can surprise you.
Quick check
- What is x XOR x?
- 0
- x
- 1
- 2x
- Which clue hints at bit manipulation?
- "find two numbers that add to a target"
- "shortest path"
- "every number appears twice except one, use O(1) space"
- "nested folders"
- What does n & (n - 1) do?
- Doubles n
- Switches off the lowest ON bit
- Reverses the bits
- Adds one