Every integer in a computer is a row of bits. Bit manipulation works on those bits directly with AND, OR, XOR, NOT and shifts, giving constant-time tricks for testing powers of two, counting set bits, toggling flags and representing an entire set as a single integer. It powers low-level systems code, compression, cryptography, Fenwick trees and bitmask DP, and it has its own distinctive family of interview problems.
Think of it like
A panel of light switches
Picture an integer as a panel of 32 light switches. A mask is a stencil laid over the panel: AND keeps only the switches the stencil exposes, OR forces the exposed ones on, XOR flips them. Shifting slides the whole pattern left or right. And if each switch stands for a guest, the panel is a guest list: one number describes exactly who is invited.
Binary representation
Binary is positional notation in base 2. Bit i (counting from 0 at the right, the least significant bit) is worth 2ⁱ. So 13 = 8 + 4 + 1 = 1101₂. A w-bit unsigned integer holds values from 0 to 2ʷ − 1.
| Decimal | Binary (8-bit) | Hex |
|---|---|---|
| 0 | 00000000 | 0x00 |
| 1 | 00000001 | 0x01 |
| 5 | 00000101 | 0x05 |
| 13 | 00001101 | 0x0D |
| 127 | 01111111 | 0x7F |
| 128 | 10000000 | 0x80 |
| 255 | 11111111 | 0xFF |
Two's complement: negative numbers
Signed integers are stored in two's complement: the top bit has a negative weight of −2^(w−1) and all other bits keep their usual positive weights. To negate a number, flip every bit and add one: −x = ~x + 1.
| Value | 8-bit two's complement | How to get it |
|---|---|---|
| 127 | 01111111 | Largest positive: 2⁷ − 1 |
| 1 | 00000001 | |
| 0 | 00000000 | Only one zero, unlike sign-magnitude |
| −1 | 11111111 | ~1 + 1 = 11111110 + 1 |
| −5 | 11111011 | ~00000101 + 1 = 11111010 + 1 |
| −128 | 10000000 | Smallest value: −2⁷, has no positive partner |
- One representation of zero, and the same adder circuit handles signed and unsigned addition.
- Range is asymmetric: a 32-bit
intspans −2,147,483,648 to 2,147,483,647. ~x = −x − 1for every integer, which explains why~0is−1and~12is−13.
The operators
| Operator | Symbol | Each result bit is 1 when... | Example with a = 1100, b = 1010 |
|---|---|---|---|
| AND | & | both bits are 1 | 1100 & 1010 = 1000 (12 & 10 = 8) |
| OR | | | at least one bit is 1 | 1100 | 1010 = 1110 (14) |
| XOR | ^ | the bits differ | 1100 ^ 1010 = 0110 (6) |
| NOT | ~ | the bit was 0 (flip all) | ~12 = −13 |
| Left shift | << | bits move left k places, zeros fill in | 12 << 2 = 48 (times 4) |
| Right shift | >> | bits move right k places | 12 >> 2 = 3 (floor of 12 / 4) |
| Goal | Expression | Why it works |
|---|---|---|
| Test bit i | (x >> i) & 1 | Move bit i to position 0, then mask it |
| Set bit i | x | (1 << i) | OR with 1 forces the bit on |
| Clear bit i | x & ~(1 << i) | AND with a mask that has a single 0 |
| Toggle bit i | x ^ (1 << i) | XOR with 1 flips the bit |
| Mask of the low k bits | (1 << k) - 1 | 1 << k is 1 followed by k zeros; subtract 1 |
| Clear the lowest set bit | x & (x - 1) | Subtracting 1 flips the lowest 1 and the zeros below it |
| Isolate the lowest set bit | x & -x | -x = ~x + 1 agrees with x only at that bit |
Shifts: arithmetic vs logical
x << k multiplies by 2ᵏ as long as nothing overflows. Right shifts come in two flavors. A logical shift fills the vacated high bits with zeros. An arithmetic shift copies the sign bit, so it computes ⌊x / 2ᵏ⌋ for negative numbers too.
Arithmetic right shift (>>)
- Fills with copies of the sign bit
-16 >> 2is-4-7 >> 1is-4: rounds toward −∞- Integer division
-7 / 2gives-3in C and Java: rounds toward 0
Logical right shift (>>> in Java and JS)
- Always fills with zeros
- Treats the bits as unsigned
-16 >>> 2is1073741820for a 32-bit int- Needed for hashing, bit reversal and unsigned arithmetic
| Language | >> on a signed value | How to shift logically |
|---|---|---|
| Java | Arithmetic | >>> for int and long |
| JavaScript / TypeScript | Arithmetic on 32-bit ints | >>> (result is an unsigned 32-bit value) |
| C / C++ | Arithmetic in practice; guaranteed since C++20 | Cast to an unsigned type first |
| Python | Arithmetic (floor) on unbounded ints | Mask first: (x & 0xFFFFFFFF) >> k |
Classic tricks
x & (x − 1): drop the lowest set bit
| Expression | Binary | Decimal |
|---|---|---|
| x | 01011000 | 88 |
| x − 1 | 01010111 | 87 |
| x & (x − 1) | 01010000 | 80 |
| −x | 10101000 | −88 |
| x & −x | 00001000 | 8 |
- Power of two:
x > 0 && (x & (x - 1)) == 0. A power of two has exactly one set bit, so dropping it leaves zero. - Lowest set bit:
x & -xis the building block of Fenwick Trees (BIT), where it gives the size of the range each node covers. - Brian Kernighan's count: repeat
x &= x - 1until zero; the number of iterations is the number of set bits, so it runs in O(set bits) instead of O(word size).
XOR tricks
- Single number: if every value appears twice except one, XOR everything. Pairs cancel (
a ^ a = 0) and the loner remains. O(n) time, O(1) space. - Missing number: XOR all indices 0..n with all values in an array holding n distinct numbers from 0..n. Everything present cancels, leaving the missing one.
- Two singles: if two values appear once,
x = a ^ bis non-zero. Split the array by the bitx & -xand XOR each half separately to recoveraandb. - Swap without a temporary:
a ^= b; b ^= a; a ^= b. A party trick: it breaks ifaandbrefer to the same memory (the value becomes 0) and is not faster than a normal swap. - Opposite signs:
(x ^ y) < 0is true exactly when x and y have different sign bits. - Gray code:
i ^ (i >> 1)produces a sequence where consecutive values differ in exactly one bit.
Bitmasks as sets
An n-bit integer can represent any subset of {0, 1, …, n − 1}: bit i is 1 exactly when element i is in the set. Set operations become single machine instructions, and a whole subset fits in a register or an array index.
| Set operation | Bitmask expression |
|---|---|
| Empty set / full set | 0 / (1 << n) - 1 |
| Add element i | s | (1 << i) |
| Remove element i | s & ~(1 << i) |
| Contains i? | (s >> i) & 1 |
| Union / intersection | a | b / a & b |
| Difference a minus b | a & ~b |
| Complement within n elements | ~s & ((1 << n) - 1) |
| Size | popcount(s) |
| Is a a subset of b? | (a & b) == a |
Enumerating every subset
Counting mask from 0 to 2ⁿ − 1 visits every subset exactly once, because every n-bit pattern appears once. Decoding each mask costs O(n), so listing all subsets is O(n · 2ⁿ). That is fine for n ≤ 20 (about 2 × 10⁷ steps) and hopeless beyond about 30.
items = ["a", "b", "c"]
n = len(items)
for mask in range(1 << n): # 0 .. 2^n - 1
print(format(mask, "03b"), [items[i] for i in range(n) if (mask >> i) & 1])
# Every non-empty submask of a given mask, largest first
mask = 0b1011
sub = mask
while sub:
print(format(sub, "04b")) # 1011, 1010, 1001, 1000, 0011, 0010, 0001
sub = (sub - 1) & maskBitmasks also make great DP states. The traveling salesman problem on n ≤ 20 cities uses dp[mask][last] ("the cheapest way to visit exactly the cities in mask, ending at last"), an O(2ⁿ · n²) algorithm that beats the O(n!) brute force by an astronomical margin.
Language pitfalls
- Python integers are unbounded. Negative numbers behave as if they had infinitely many leading 1s, so
bin(-5)prints-0b101,x >> 1never turns a negative number into a large positive one, and Kernighan's loop never ends for negative input. To emulate 32-bit behavior, mask with0xFFFFFFFFand convert back withx - (1 << 32) if x >= 1 << 31 else x. - Java has no unsigned
int.1 << 31is negative,bytevalues are signed (useb & 0xFF), and arithmetic silently wraps on overflow. - C and C++: signed overflow and over-wide shifts are undefined behavior, so prefer
uint32_tanduint64_tfor bit work.__builtin_popcounttakes anunsigned int; use__builtin_popcountllfor 64-bit values. - JavaScript and TypeScript convert operands of bitwise operators to 32-bit signed integers.
x >>> 0reinterprets as unsigned; for wider masks useBigInt(1n << 40n). - Operator precedence in C, C++, Java and JavaScript puts
==above&, sox & 1 == 0meansx & (1 == 0). Python ranks&above comparisons, which hides the bug when you switch languages. Always parenthesize:(x & 1) == 0.
Where bits are used in practice
- Permission and feature flags: Unix file modes pack read, write and execute into bits worth 4, 2 and 1, which is why
chmod 755works. - Bitsets and bitboards: chess engines represent each piece type as a 64-bit board, and a bitset stores a set of small integers in 1 bit each.
- Probabilistic structures: Bloom filters (Bloom Filters & Probabilistic Structures) are bit arrays indexed by several hash functions.
- Networking: subnet masks such as
255.255.255.0select the network part of an IP address with a single AND. - Hashing and checksums: hash functions and CRCs mix data with shifts, rotations and XOR.
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| AND, OR, XOR, NOT, shift on a machine word | O(1) | O(1) | Single CPU instruction |
| Test, set, clear or toggle bit i | O(1) | O(1) | One shift plus one logical operation |
| Popcount, Kernighan loop | O(k) | O(1) | k = number of set bits |
| Popcount, checking every bit | O(w) | O(1) | w = word size, usually 32 or 64 |
| Single number via XOR | O(n) | O(1) | One pass, no hash set |
| Enumerate all subsets of n items | O(n · 2ⁿ) | O(n) | Practical up to n ≈ 20 to 25 |
| Enumerate submasks of every mask | O(3ⁿ) | O(1) | Basis of subset DP |
"O(1)" assumes values fit in a machine word. Python's unbounded integers cost O(number of bits) per operation for very large values.
Implementation
Single-bit operations, the power-of-two test, Kernighan's popcount, the lowest set bit, and the XOR tricks for the single and missing number problems.
def get_bit(x: int, i: int) -> int:
return (x >> i) & 1
def set_bit(x: int, i: int) -> int:
return x | (1 << i)
def clear_bit(x: int, i: int) -> int:
return x & ~(1 << i)
def toggle_bit(x: int, i: int) -> int:
return x ^ (1 << i)
def is_power_of_two(x: int) -> bool:
return x > 0 and (x & (x - 1)) == 0
def count_bits(x: int) -> int:
"""Brian Kernighan: one iteration per set bit. x must be non-negative."""
count = 0
while x:
x &= x - 1 # clear the lowest set bit
count += 1
return count
def lowest_set_bit(x: int) -> int:
return x & -x # 0b1011000 -> 0b1000
def single_number(nums: list[int]) -> int:
"""Every value appears twice except one: pairs cancel under XOR."""
result = 0
for x in nums:
result ^= x
return result
def missing_number(nums: list[int]) -> int:
"""nums holds n distinct values from 0..n with exactly one missing."""
result = len(nums)
for i, x in enumerate(nums):
result ^= i ^ x
return result
print(is_power_of_two(64), count_bits(0b1011000), lowest_set_bit(88)) # True 3 8
print(single_number([4, 1, 2, 1, 2]), missing_number([3, 0, 1])) # 4 2Key takeaways
- Integers are bit vectors; signed values use two's complement, where
−x = ~x + 1and the range is asymmetric. - Seven one-liners cover most needs: test, set, clear and toggle a bit, the low-k mask,
x & (x − 1)andx & −x. - XOR is its own inverse, which solves single-number, missing-number and two-singles problems in O(1) extra space.
- An n-bit mask represents a subset; counting from 0 to 2ⁿ − 1 enumerates the power set in O(n · 2ⁿ).
- Know your language: Python ints are unbounded, Java has
>>>and no unsigned int, C++ has undefined behavior on signed overflow and over-wide shifts.
Common pitfalls
- Writing
x & 1 == 0in C-family languages, where==binds tighter than&. Always parenthesize. - Using
1 << kfor k ≥ 31 in a 32-bit type instead of1L << kor1ULL << k. - Running Kernighan's loop or right-shift loops on negative Python integers, which never reach zero.
- Assuming
>>divides like/for negative numbers:−7 >> 1is −4, while−7 / 2is −3 in C and Java. - Using the XOR swap on two references to the same memory location, which zeroes the value.
Interview tips
- When asked for O(1) extra space with paired duplicates, XOR should be your first thought.
- Explain why
x & (x − 1)works by showing the borrow: subtracting 1 flips the lowest 1 and every 0 below it. - For "all subsets" with n ≤ 20, offer both recursion and the bitmask loop; mention O(n · 2ⁿ).
- Call out language specifics unprompted (Python's unbounded ints, Java's
>>>); it signals real-world experience.
Real-world applications
- Permission flags, feature toggles and compact boolean arrays (bitsets).
- Fenwick trees (lowest set bit), bitmask DP and chess engines (bitboards).
- Bloom filters, hash functions, checksums and compression.
- Networking (subnet masks) and graphics (color channels packed into 32-bit integers).
Practice problems
Test yourself
What does x & (x - 1) compute?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.