bitarray_count.c (559B)
1 /* ISC license. */ 2 3 #include <skalibs/bitarray.h> 4 5 #define B0(n) n, n+1, n+1, n+2 6 #define B1(n) B0(n), B0(n+1), B0(n+1), B0(n+2) 7 #define B2(n) B1(n), B1(n+1), B1(n+1), B1(n+2) 8 #define B3(n) B2(n), B2(n+1), B2(n+1), B2(n+2) 9 10 size_t bitarray_countones (unsigned char const *c, size_t n) 11 { 12 static unsigned char const table[256] = { B3(0) } ; 13 size_t len = bitarray_div8(n) ; 14 size_t total = 0 ; 15 size_t i = 0 ; 16 if (n & 7) len-- ; 17 for (; i < len ; i++) total += table[c[i]] ; 18 if (n & 7) total += table[c[i] & ((1 << (n & 7)) - 1)] ; 19 return total ; 20 }