]> mj.ucw.cz Git - libucw.git/blob - ucw/bit-count.c
UCW::CGI: Documented the changes
[libucw.git] / ucw / bit-count.c
1 /*
2  *      UCW Library -- Counting bits in bitarray
3  *
4  *      (c) 2012 Pavel Charvat <pchar@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/bitops.h>
12 #include <ucw/bitarray.h>
13
14 uns bit_array_count_bits(bitarray_t a, uns n)
15 {
16   uns m = 0;
17   n = BIT_ARRAY_WORDS(n);
18   while (n--)
19     m += bit_count(*a++);
20   return m;
21 }
22
23 #ifdef TEST
24
25 #include <stdio.h>
26 #include <alloca.h>
27
28 int main(void)
29 {
30   char buf[1024];
31   bitarray_t a = alloca(BIT_ARRAY_BYTES(sizeof(buf)));
32   while (1)
33     {
34       if (!fgets(buf, sizeof(buf), stdin))
35         return 0;
36       uns n;
37       for (n = 0; buf[n] == '0' || buf[n] == '1'; n++);
38       bit_array_zero(a, n);
39       for (uns i = 0; i < n; i++)
40         if (buf[i] == '1')
41           bit_array_set(a, i);
42       printf("%u\n", bit_array_count_bits(a, n));
43     }
44 }
45
46 #endif