The decrement test for a power of two can be modified to count bits and runs in log n time.
int bits(unsigned n)
{
int i = 0;
while (n > 0) { n &= n-1; i++ }
return i;
}