box-o-sand/oldstuff/PracticingC/gowrikumar/src/07-countbits.c

41 lines
680 B
C

/**
* :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
*/