Created
October 30, 2009 11:38
-
-
Save shaobin0604/222277 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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