# HG changeset patch # User Louis Opter # Date 1373770031 25200 # Node ID 9748b64edb26606431ab00bda1192920c698b2b5 # Parent 1f4c37678f692992e0be00cbca86737f0a3bf042 Add the bit count exercise diff -r 1f4c37678f69 -r 9748b64edb26 arrays/bit_count/bit_count.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arrays/bit_count/bit_count.c Sat Jul 13 19:47:11 2013 -0700 @@ -0,0 +1,37 @@ +#include +#include + +/* + * There is different solutions but this one is simple and easy to remember + * (it's very similar to !(a & (a - 1)) used to check if a is a power of two). + * If you want to look smart, say that this solution is perfect for embedded + * systems. + * + * Another simple one, more optimized, is to have a lookup table that gives you + * the number of 1 bit in each integer for integers from 0 to 255 (or 0 to + * 2**16 - 1). + */ + +unsigned int +bit_count(const unsigned char *a, size_t n) +{ + unsigned int c = 0; + + while (n--) + for (unsigned char v = a[n]; v; v &= v - 1) + c++; + + return c; +} + +int +main(void) +{ + int a[] = { 1, 2, 3, 4 }; + int b = 42; + + printf("%d\n", bit_count((unsigned char *)a, sizeof(a))); + printf("%d\n", bit_count((unsigned char *)&b, sizeof(b))); + + return 0; +} diff -r 1f4c37678f69 -r 9748b64edb26 arrays/bit_count/hints.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arrays/bit_count/hints.rst Sat Jul 13 19:47:11 2013 -0700 @@ -0,0 +1,4 @@ +Hints +===== + +This is actually probably easier in C. diff -r 1f4c37678f69 -r 9748b64edb26 arrays/bit_count/question.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arrays/bit_count/question.rst Sat Jul 13 19:47:11 2013 -0700 @@ -0,0 +1,5 @@ +Bit Count +========= + +Write a function that returns the number of bits set to 1 in the given memory +area of size n.