Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 30, 2009 11:38
Show Gist options
  • Save shaobin0604/222277 to your computer and use it in GitHub Desktop.
Save shaobin0604/222277 to your computer and use it in GitHub Desktop.
/*
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment