Home / Learn Embedded C / Counting Set Bits
Counting Set Bits
How many bits in a value are 1 — used in checksums, parity and diagnostics.
What's actually going on
The basic idea
Counting set bits ("population count") answers "how many of these bits are 1?" — used for parity checks, simple checksums, and diagnostics like "how many sensors reported in this cycle".
Why this comes up
A simple parity bit (even/odd number of 1 bits) is one of the oldest and simplest error-detection techniques in digital communication, and directly depends on counting set bits.
The mechanics
The simplest approach checks one bit at a time in a loop; faster bit-trick approaches exist (like Brian Kernighan's "x &= x - 1" trick, which clears the lowest set bit each iteration) for when performance matters.
Where it is used
- Parity/error checking
- Simple checksums
- Diagnostics and counters
Try it
This value has an odd number of set bits — relevant if you were computing an even-parity check bit for it.
int count_set_bits(unsigned int x) {
int count = 0;
while (x) {
x &= (x - 1); /* clears the lowest set bit each time */
count++;
}
return count;
}Try it: Kernighan's trick counted by hand
This loop runs only once per set bit (not once per bit position), so it finishes faster than the position-by-position loop for sparse values.
Quick check
1. What is one real use of counting the number of set bits in a value?
A parity bit is based directly on whether the number of set bits is even or odd.