]> mj.ucw.cz Git - libucw.git/blob - ucw/bit-array.c
tableprinter: definition of the table separated from handle
[libucw.git] / ucw / bit-array.c
1 /*
2  *      UCW Library -- Support routines for bitarray
3  *
4  *      (c) 2012 Pavel Charvat <pchar@ucw.cz>
5  *      (c) 2013 Martin Mares <mj@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include <ucw/lib.h>
12 #include <ucw/bitops.h>
13 #include <ucw/bitarray.h>
14
15 uint bit_array_count_bits(bitarray_t a, uint n)
16 {
17   uint m = 0;
18   n = BIT_ARRAY_WORDS(n);
19   while (n--)
20     m += bit_count(*a++);
21   return m;
22 }
23
24 bitarray_t bit_array_xrealloc(bitarray_t a, uint old_n, uint new_n)
25 {
26   uint old_bytes = BIT_ARRAY_BYTES(old_n);
27   uint new_bytes =  BIT_ARRAY_BYTES(new_n);
28   if (old_bytes == new_bytes)
29     return a;
30   a = xrealloc(a, new_bytes);
31   if (old_bytes < new_bytes)
32     bzero(a + old_bytes, new_bytes - old_bytes);
33   return a;
34 }
35
36 #ifdef TEST
37
38 #include <stdio.h>
39 #include <alloca.h>
40
41 int main(void)
42 {
43   char buf[1024];
44   bitarray_t a = alloca(BIT_ARRAY_BYTES(sizeof(buf)));
45   while (1)
46     {
47       if (!fgets(buf, sizeof(buf), stdin))
48         return 0;
49       uint n;
50       for (n = 0; buf[n] == '0' || buf[n] == '1'; n++);
51       bit_array_zero(a, n);
52       for (uint i = 0; i < n; i++)
53         if (buf[i] == '1')
54           bit_array_set(a, i);
55       printf("%u\n", bit_array_count_bits(a, n));
56     }
57 }
58
59 #endif