/*
* Exercise 2-9. In a two's complement number system, x &= (x-1) deletes the
* right most 1-bit in x. Explain why. Use this observation to write a faster
* version of bitcount.
*/
#include <stdio.h>
int bitcount(unsigned int x);
int bitcount(unsigned int x) {
int i = 0;
while (x != 0) {
i++;
x = x & (x - 1);
}
return i;
}
int main(void) {
unsigned int x = 0xff;
int r = 8;
if (r == bitcount(x))
printf("assert success!\n");
else
printf("assert fail!\n");
return 0;
}