diff --git a/gowrikumar/src/07b-countbits.c b/gowrikumar/src/07b-countbits.c new file mode 100644 index 0000000..e363587 --- /dev/null +++ b/gowrikumar/src/07b-countbits.c @@ -0,0 +1,67 @@ +/** + * :author: Dan Buch (daniel.buch@gmail.com) + */ + +#include + +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 + */