There are several options on the bit-twiddling hacks page.
Of course, you could argue that iterating over all 32 possible bits is O (N), since it has the same cost every time :)
For simplicity, I would consider the lookup-table-per-byte approach or Brian Kernigan’s clear idea, which repeats as many times as there is a bit that I would write as:
public static int CountBits(uint value) { int count = 0; while (value != 0) { count++; value &= value - 1; } return count; }
If you don't like the idea of populating a lookup table with 256 entries, browsing for nybble will still be pretty fast. Keep in mind that it is possible that searching in 8 arrays may be slower than 32 simple bit operations.
Of course, it is worth checking the real performance of your application before moving on to especially esoteric approaches ... is this really a bottleneck for you?
source share