The best method for counting bits in a 32-bit integer(2)
long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/