[PATCH] Modified log to base2 calculation

Frodo Baggins (none) frodo at ZION.
Sun Nov 11 19:28:15 UTC 2007


Algorithm taken from wikipedia (http://en.wikipedia.org/wiki/Binary_logarithm).
---
 libparted/exception.c |   19 ++++++++++++-------
 1 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/libparted/exception.c b/libparted/exception.c
index d9425a3..5210fed 100644
--- a/libparted/exception.c
+++ b/libparted/exception.c
@@ -103,16 +103,21 @@ ped_exception_get_type_string (PedExceptionType ex_type)

 /* FIXME: move this out to the prospective math.c */
 /* FIXME: this can probably be done more efficiently */
+/*
+ * Returns the floor form of binary logarithm for a 32 bit integer.
+ * -1 is returned if n is 0.
+ */
 static int
 ped_log2 (int n)
 {
-       int x;
-
-        PED_ASSERT (n > 0, return -1);
-
-       for (x=0; 1 << x <= n; x++);
-
-       return x - 1;
+       int pos = 0;
+       if (n >= 1<<16) { n >>= 16; pos += 16; }
+       if (n >= 1<< 8) { n >>=  8; pos +=  8; }
+       if (n >= 1<< 4) { n >>=  4; pos +=  4; }
+       if (n >= 1<< 2) { n >>=  2; pos +=  2; }
+       if (n >= 1<< 1) {           pos +=  1; }
+
+       return ((n == 0) ? (-1) : pos);
 }

 /**
--
1.4.4.4



More information about the parted-devel mailing list