From f20b8ca1389e20c36286eed158120c971fea720a Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 18 Jun 2011 19:37:54 -0400 Subject: [PATCH] counting bits! --- gowrikumar/src/07-countbits.c | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 gowrikumar/src/07-countbits.c diff --git a/gowrikumar/src/07-countbits.c b/gowrikumar/src/07-countbits.c new file mode 100644 index 0000000..73a72dc --- /dev/null +++ b/gowrikumar/src/07-countbits.c @@ -0,0 +1,40 @@ +/** + * :author: Dan Buch (daniel.buch@gmail.com) + */ + +#include + +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 + */