From 380d51d05a895e757242ef8ab78d87443a1fa7da Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Mon, 29 Aug 2011 14:31:22 +1000 Subject: [PATCH] Add is_pow2, round_up --- maths.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ maths.hpp | 15 +++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/maths.cpp b/maths.cpp index 99b3e30e..aae28fd5 100644 --- a/maths.cpp +++ b/maths.cpp @@ -19,9 +19,11 @@ #include "maths.hpp" +#include "enable_if.hpp" #include "float.hpp" #include +#include template @@ -33,6 +35,19 @@ template double pow2(double); template int pow2( int); +template +bool +is_pow2 (T value) { + typedef typename enable_if::value, bool>::type return_type; + return (return_type)(value && !(value & (value - 1))); +} + +template bool is_pow2 (uint8_t); +template bool is_pow2 (uint16_t); +template bool is_pow2 (uint32_t); +template bool is_pow2 (uint64_t); + + template double rootsquare (T a, T b) @@ -54,3 +69,31 @@ almost_equal (const double &a, const double &b) { return ieee_double::almost_equal (a, b); } +template +typename enable_if::value, T>::type +round_up (T value, T align) { + check_hard (align > 1); + return (value + align - 1) / align; +} + + +template +T +round_pow2 (T value) { + typedef typename enable_if::value, T>::type return_type; + + --value; + + for (unsigned i = 1; i < sizeof (T) * 8; i <<= 1) { + value |= value >> i; + } + + ++value; + return (return_type)value; +} + + +template uint8_t round_pow2 (uint8_t); +template uint16_t round_pow2 (uint16_t); +template uint32_t round_pow2 (uint32_t); +template uint64_t round_pow2 (uint64_t); diff --git a/maths.hpp b/maths.hpp index 2662704e..0bdd139d 100644 --- a/maths.hpp +++ b/maths.hpp @@ -28,11 +28,26 @@ T pow2 (T value) pure; +template +bool +is_pow2 (T value) pure; + + template double rootsquare (T a, T b) pure; +template +T +round_up (T value, T align) pure; + + +template +T +round_pow2 (T value) pure; + + /** * Check if two floating point numbers are approximately equal. Returns true * if the difference is less than a percentage of each individual value.