Bit Manipulation#
Based on The C Programming Language (TCPL), 2nd ed. Section 2.9 (Bitwise Operators), p. 50.
Bit Counting (Population Count)#
Counting the number of 1-bits in an unsigned integer.
Version 1: Linear Bit Shift#
Shifts bits rightward one by one and masks the lowest bit with 01 (octal literal for 1):
int BitCountLinear(unsigned int x) {
int b = 0;
for (; x != 0; x >>= 1) {
if (x & 01) {
b++;
}
}
return b;
}- Time Complexity: $O(N)$ where $N$ is the number of bits in the integer type (eg. up to 32 iterations).
Version 2: Brian Kernighan’s Algorithm (x &= (x - 1))#
Clears the rightmost 1-bit on each iteration:
int BitCountKernighan(unsigned int x) {
int b = 0;
while (x) {
x &= (x - 1); // Deletes the rightmost 1-bit
b++;
}
return b;
}- Core Mechanic: Subtracting
1fromxflips the lowest set bit to0and all trailing zeros to1. Performingx & (x - 1)cancels out that lowest set bit. - Time Complexity: $O(K)$ where $K$ is the count of set bits (1s). Only iterates as many times as there are 1-bits.