Fast bit counting variant

From Foochal

Jump to: navigation, search


The objective is to count the number of bits in an unsigned 32-bit integer. There are several methods described here. I wrote the following as a variation of the MIT Hackmem Count.

int tmp = n - (n >> 1 & 0x77777777) - (n >> 2 & 0x33333333) - (n >> 3 & 0x11111111);
return ((tmp + (tmp >> 4)) & 0x0F0F0F0F) % 255;

The idea is similar to the MIT hackmem count, but instead of using 3 bits, I use groups of 4 bits.


Personal tools