Binary Ones Counter
Count the number of 1-bits (Hamming weight) in any number. Supports decimal, binary, hex, and octal input with bit-level analysis.
About
The count of 1-bits in a binary representation is formally called the Hamming weight or population count (popcount). It appears in error-correcting codes, cryptographic hash analysis, combinatorial optimization, and low-level CPU instruction design. Getting it wrong in a checksum computation or a bitmask filter means silent data corruption. This tool computes the exact Hamming weight for integers of arbitrary size using Brian Kernighan's algorithm, which runs in O(k) time where k equals the number of set bits. It accepts decimal, binary (0b prefix), hexadecimal (0x), and octal (0o) input. Negative integers are not supported because two's complement width is ambiguous without a fixed register size.
Formulas
The Hamming weight (population count) of a non-negative integer n is the number of 1-bits in its binary expansion.
where bi โ {0, 1} is the i-th bit and L is the bit length of n.
Brian Kernighan's algorithm exploits the fact that n โง (n โ 1) clears the lowest set bit. Repeat until n = 0 and count iterations.
while n โ 0:
n โ n โง (n โ 1)
k โ k + 1
return k
Bit density is defined as: density = popcount(n)L ร 100%
where L = โlog2(n)โ + 1 for n > 0, and L = 1 for n = 0.
Reference Data
| Decimal | Binary | Ones Count | Bit Length | Density | Notes |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 1 | 0% | Zero case |
| 1 | 1 | 1 | 1 | 100% | Single bit |
| 7 | 111 | 3 | 3 | 100% | All ones (23 โ 1) |
| 8 | 1000 | 1 | 4 | 25% | Power of 2 |
| 15 | 1111 | 4 | 4 | 100% | All ones (nibble) |
| 42 | 101010 | 3 | 6 | 50% | Alternating pattern |
| 127 | 1111111 | 7 | 7 | 100% | Max signed 8-bit |
| 128 | 10000000 | 1 | 8 | 12.5% | Power of 2 |
| 255 | 11111111 | 8 | 8 | 100% | Full byte |
| 256 | 100000000 | 1 | 9 | 11.1% | Power of 2 |
| 1023 | 1111111111 | 10 | 10 | 100% | 210 โ 1 |
| 1024 | 10000000000 | 1 | 11 | 9.1% | 1 KiB boundary |
| 4096 | 1000000000000 | 1 | 13 | 7.7% | Page size |
| 65535 | 1111111111111111 | 16 | 16 | 100% | Full 16-bit word |
| 2147483647 | 31 ones | 31 | 31 | 100% | Max signed 32-bit |
| 4294967295 | 32 ones | 32 | 32 | 100% | Max unsigned 32-bit |
| 3735928559 | 0xDEADBEEF | 24 | 32 | 75% | Classic debug marker |
| 3405691582 | 0xCAFEBABE | 22 | 32 | 68.8% | Java class magic number |
| 48879 | 0xBEEF | 12 | 16 | 75% | Common test value |
| 170 | 10101010 | 4 | 8 | 50% | 0xAA alternating |