int bitCount(int x) {
/* We start by counting the number of bits in each byte. We count all bits
* in by hand, by shifting and masking in parallel.
* Once we've counted all bits in every byte, we sum the count by shifting
* every byte.
*/
int mask1 = 0x1 | 0x1 << 8 | 0x1 << 16 | 0x1 << 24;
int mask2 = 0xFF;
x = (x & mask1) + ((x >> 1) & mask1) + ((x >> 2) & mask1) + \
((x >> 3) & mask1) + ((x >> 4) & mask1) + ((x >> 5) & mask1) +\
((x >> 6) & mask1) + ((x >> 7) & mask1);
x = (x & mask2) + ((x >> 8) & mask2) + ((x >> 16) & mask2) + ((x >> 24) & mask2);
return x;
}