commit 1129cb29161e60fb1530afed29d06e8e1782ef31
parent b8d6272e6e4668e9dfa425eb6bf68f9cb2a018ba
Author: vaplv <vaplv@free.fr>
Date: Sat, 3 May 2014 16:45:26 +0200
Add and test the log2i function
Diffstat:
3 files changed, 18 insertions(+), 2 deletions(-)
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
@@ -116,7 +116,7 @@ new_test(test_library rsys)
new_test(test_list rsys)
new_test(test_mem_allocator rsys)
new_test(test_binary_heap rsys)
-new_test(test_math)
+new_test(test_math m)
new_test(test_ref)
new_test(test_signal rsys)
new_test(test_str rsys)
diff --git a/src/math.h b/src/math.h
@@ -12,7 +12,6 @@
#define RCP_PI 0.31830988618379067154 /* 1/ pi */
#define SQRT2 1.41421356237309504880 /* sqrt( 2 ) */
-
static FINLINE size_t
round_up_pow2(const size_t i)
{
@@ -29,6 +28,15 @@ round_up_pow2(const size_t i)
}
}
+static FINLINE int
+log2i(const int i)
+{
+ union { float f; const int32_t i; } ucast;
+ ASSERT(i != 0);
+ ucast.f = (float)i;
+ return ((ucast.i>>23/*#bits mantissa*/) & ((1<<8/*#bits exponent*/)-1)) - 127;
+}
+
static FINLINE float
absf(const float flt)
{
diff --git a/src/test_math.c b/src/test_math.c
@@ -36,6 +36,14 @@ main(int argc, char** argv)
CHECK(IS_POW2(31), 0);
CHECK(IS_POW2(64), 1);
CHECK(IS_POW2(1 << 16), 1);
+ CHECK(log2i(3), 1);
+ CHECK(log2i(4), 2);
+ CHECK(log2i(5), 2);
+ CHECK(log2i(7), 2);
+ CHECK(log2i(8), 3);
+ CHECK(log2i(12), 3);
+ CHECK(log2i(511), 8);
+ CHECK(log2i(512), 9);
CHECK(round_up_pow2(0), 1);
CHECK(round_up_pow2(3), 4);
CHECK(round_up_pow2(4), 4);