I\'m looking for the fastest way of counting the number of bit transitions in an unsigned int.
unsigned int
If the int contains: 0b0000000000000000000000000000101
0b0000000000000000000000000000101
Here's the code using arithmetic shift + xor and Kernighan's method for bit counting:
int count_transitions(int x) { assert((-1 >> 1) < 0); // check for arithmetic shift int count = 0; for(x ^= (x >> 1); x; x &= x - 1) ++count; return count; }