counting bits!

This commit is contained in:
Dan Buch 2011-06-18 19:37:54 -04:00
parent a414f515d1
commit f20b8ca138

View File

@ -0,0 +1,40 @@
/**
* :author: Dan Buch (daniel.buch@gmail.com)
*/
#include <stdio.h>
static unsigned int mask[] = {
0x55555555,
0x33333333,
0x0F0F0F0F,
0x00FF00FF,
0x0000FFFF
};
int get_bit_count(unsigned int x)
{
int i;
int shift; /* Number of positions to shift to right*/
for (i = 0, shift = 1; i < 5; i++, shift *= 2) {
x = (x & mask[i])+ ((x >> shift) & mask[i]);
}
return x;
}
int main()
{
int to_test[] = {0, 5, 7};
int current;
for (int i = 0; i < 3 ; i++) {
current = to_test[i];
printf("get_bit_count(%d) = %d\n", current, get_bit_count(current));
}
}
/* vim:filetype=c:fileencoding=utf-8
*/