From 755e0d92cb9121938d63952d80f61338c179ca15 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Thu, 11 Sep 2014 15:34:59 +1000 Subject: [PATCH] maths: add log2 --- maths.cpp | 20 ++++++++++++++++++++ maths.hpp | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/maths.cpp b/maths.cpp index b679468d..8c9d49a1 100644 --- a/maths.cpp +++ b/maths.cpp @@ -40,6 +40,26 @@ template bool is_pow2 (uint32_t); template bool is_pow2 (uint64_t); +//----------------------------------------------------------------------------- +template +T +log2 (T v) { + static_assert (std::is_integral::value, + "log2 is only implemented for integers"); + + T l = 0; + while (v) { + v >>= 1; + l += 1; + } + + return l; +} + +template uint32_t log2 (uint32_t); +template uint64_t log2 (uint64_t); + + //----------------------------------------------------------------------------- template double diff --git a/maths.hpp b/maths.hpp index 815f3987..19c44d75 100644 --- a/maths.hpp +++ b/maths.hpp @@ -36,6 +36,11 @@ bool is_pow2 (T value) pure; +template +T +log2 (T val) pure; + + template double rootsquare (T a, T b) pure;