Add a routine to count the number of set bits in a bitset.
authorDavid Given <dg@cowlark.com>
Sat, 4 Feb 2017 22:08:52 +0000 (23:08 +0100)
committerDavid Given <dg@cowlark.com>
Sat, 4 Feb 2017 22:08:52 +0000 (23:08 +0100)
modules/src/data/bitmap.c
modules/src/data/bitmap.h

index d47684d..dff7db1 100644 (file)
@@ -85,3 +85,30 @@ int bitmap_find_unset_bit(unsigned int* bitmap, int size)
 
        return -1;
 }
+
+static int count_bits_in_word(unsigned int word)
+{
+       int i = 0;
+       while (word)
+       {
+               if (word & 1)
+                       i++;
+               word >>= 1;
+       }
+       return i;
+}
+
+int bitmap_count_set_bits(unsigned int* bitmap, int size)
+{
+       int word;
+       int words = ((size-1) / BITS_PER_WORD) + 1;
+       int count = 0;
+
+       for (word=0; word<words; word++)
+       {
+               unsigned int w = bitmap[word];
+               count += count_bits_in_word(w);
+       }
+
+       return count;
+}
index 999bb7e..65ead3f 100644 (file)
@@ -9,6 +9,7 @@ extern int bitmap_findfirst(unsigned int* bitmap, int size);
 extern void bitmap_and(unsigned int* dest, int size, unsigned int* src);
 extern void bitmap_or(unsigned int* dest, int size, unsigned int* src);
 extern int bitmap_find_unset_bit(unsigned int* bitmap, int size);
+extern int bitmap_count_set_bits(unsigned int* bitmap, int size);
 
 #define BITS_PER_WORD (sizeof(unsigned int)*8)
 #define WORDS_FOR_BITMAP_SIZE(n) (((n-1) / BITS_PER_WORD) + 1)