Browse Source

Refactoring and comments for prev_pow2()

Ioannis Koutras 13 years ago
parent
commit
cd1d5a42a1
1 changed files with 16 additions and 8 deletions
  1. 16 8
      src/bitmap/bitmap_other.c

+ 16 - 8
src/bitmap/bitmap_other.c

@@ -77,15 +77,23 @@ void add_arrays(BMAP_EL_TYPE *array1, BMAP_EL_TYPE *array2, size_t elements) {
     }
 }
 
-/** Compute the power of 2 which is <= n */
+/** Compute the previous power of 2 which is <= n */
 size_t prev_pow2(size_t n) {
-	n |= n >> 1;
-	n |= n >> 2;
-	n |= n >> 4;
-	n |= n >> 8;
-	n |= n >> 16;
-	n |= n >> 32;
-	return ((n >> 1) + 1);
+    unsigned int last_for_n_bits, i;
+
+    /* size_t is the data type of the argument
+     *
+     * We multiply it by 8 to get the bits and then divide it by 2 to get the
+     * previous size, ergo multiply by 4.
+     */
+    last_for_n_bits = sizeof(size_t) * 4;
+    i = 1;
+
+    while(i <= last_for_n_bits) {
+        n |= n >> i;
+    }
+
+    return ((n >> 1) + 1);
 }
 
 /** Makes a bit mask of 1's