Next: Skip white space Up: Idiomatic C Previous: Idiomatic C

bitcount()

This function is designed to count the 1's in a bit pattern.

int bit_count(unsigned x)
   {

   int b;

   for (b = 0;  x != 0;  x >>= 1)
	if (x & 01)  b++;

   return b;
   }

Note: the for-loop initialises b, but tests and updates x. b is updated conditionally in the body of the loop.

Note: the if works because FALSE is zero.



Next: Skip white space Up: Idiomatic C Previous: Idiomatic C


maspjw@
Tue Sep 27 15:29:34 BST 1994