Counting the Set Bits in a Word
Population count adds one for every bit position holding one. Specify a finite width if a negative value is represented with sign extension.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a small mask
The unsigned word 10110100 has four set bits. Counting those positions describes the size of a subset when bits stand for choices. Power sets and bit patterns establish that correspondence.
Check negative semantics
The four-bit pattern of minus one has four ones. Its eight-bit representation has eight. An integer library may instead count ones in the absolute value. See sign extension for why those widths differ.[1]
Walk the word by removing one set bit at a time
For a positive fixed-width word \(x\), clearing its least significant set bit can use \(x\mathbin{\&}(x-1)\). Subtracting one turns that set bit off and makes all less significant positions one. AND leaves those positions zero because they were zero in the original. See masking with AND.
101100 → 101000 → 100000 → 000000
One set bit cleared per step
Population count of original: 3
Define treatment of zero and negative values
Zero requires zero clearing steps. For a signed input, the count of set positions depends on the width chosen for its bit pattern. Normalize to that width before calling a bit operation meant for unsigned data.