a more verbose version of the bit counter

This commit is contained in:
Dan Buch 2011-06-18 19:57:39 -04:00
parent b447c7a61a
commit 9ab4fa7279

View File

@ -0,0 +1,67 @@
/**
* :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)
{
printf("get_bit_count(%d)\n", x);
int i;
int x_and_mask;
int x_shifted;
int x_shifted_and_mask;
int shift; /* Number of positions to shift to right*/
for (i = 0, shift = 1; i < 5; i++, shift *= 2) {
printf(" START loop\n");
printf(" i = %d, x = %d, shift = %d\n", i, x, shift);
x_and_mask = x & mask[i];
printf(" x & mask[i] = %d\n", x_and_mask);
x_shifted = x >> shift;
printf(" x >> shift = %d\n", x_shifted);
x_shifted_and_mask = x_shifted & mask[i];
printf(" (x >> shift) & mask[i] = %d\n", x_shifted_and_mask);
x = x_and_mask + x_shifted_and_mask;
printf(" x = %d\n", x);
printf(" END loop\n");
}
return x;
}
int main()
{
int to_test[] = {0, 5, 7};
int current;
/*
size_t mask_len = sizeof(mask) / sizeof(unsigned int);
for (int i = 0; i < mask_len; i++) {
printf("mask[%d] = %d\n", i, mask[i]);
}
*/
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
*/