Population count, also known as the Hamming weight or simply popcount, answers a deceptively useful question: how many bits in this number are set to 1? This tool computes it for any non-negative integer entered in decimal, hex, or binary, and shows the binary form so you can verify the count by eye.
How it works
The tool counts set bits using Kernighan’s bit-clearing trick rather than checking every bit position individually:
count = 0
while x != 0:
x = x & (x - 1) // clears the lowest set bit
count += 1
Subtracting 1 from x flips the lowest set bit to 0 and turns every zero below
it into 1. ANDing that result with the original x clears the lowest set bit
(and everything below) in one step. The loop therefore runs exactly once per
set bit, not once per bit position — making it fast when set bits are sparse.
The zero count shown is the number of zero bits within the minimal width needed to
write the number, since leading zeros are theoretically infinite.
Worked example
The decimal value 182 is 10110110 in binary:
| Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 0 | 1 | 1 | 0 |
Five positions are 1, so the population count is 5. The remaining three
positions are 0, giving three zero bits across the eight-bit width.
Tracing Kernighan’s loop:
| Step | x (binary) | x & (x-1) | Bits cleared |
|---|---|---|---|
| 1 | 10110110 | 10110100 | bit 1 |
| 2 | 10110100 | 10110000 | bit 2 |
| 3 | 10110000 | 10100000 | bit 4 |
| 4 | 10100000 | 10000000 | bit 5 |
| 5 | 10000000 | 00000000 | bit 7 |
Five iterations, five set bits — the loop halts.
Where popcount is used
- Bitboard engines (chess, draughts): counting pieces on a 64-bit board in a single instruction.
- Error-correcting codes: Hamming distance between two codewords equals the popcount of their XOR — if two words differ in three bit positions, their XOR has a population count of 3.
- Bloom filters: monitoring how many bits are set to estimate the filter’s saturation before false-positive rates climb.
- Similarity hashing: comparing SimHash fingerprints of documents by their Hamming distance to cluster near-duplicates.
- Cryptography: certain side-channel attacks exploit differences in power consumption that correlate with popcount, so constant-time implementations avoid data-dependent loops.
Modern CPUs expose this natively: the POPCNT instruction on x86/x64 and the
CNT instruction on ARM can count set bits in a 64-bit register in a single
clock cycle. This calculator uses JavaScript BigInt, so there is no 32- or
64-bit limit — you can analyse numbers hundreds of digits long.