Mercurial > hg > qm-dsp
diff maths/MathUtilities.cpp @ 55:7fe29d8a7eaf
* Various fixes related to the bar estimator code
author | cannam |
---|---|
date | Tue, 10 Feb 2009 16:37:11 +0000 |
parents | 5bec06ecc88a |
children | d72fcd34d9a7 |
line wrap: on
line diff
--- a/maths/MathUtilities.cpp Tue Feb 10 12:52:43 2009 +0000 +++ b/maths/MathUtilities.cpp Tue Feb 10 16:37:11 2009 +0000 @@ -353,4 +353,39 @@ } } - +bool +MathUtilities::isPowerOfTwo(int x) +{ + if (x < 2) return false; + if (x & (x-1)) return false; + return true; +} + +int +MathUtilities::nextPowerOfTwo(int x) +{ + if (isPowerOfTwo(x)) return x; + int n = 1; + while (x) { x >>= 1; n <<= 1; } + return n; +} + +int +MathUtilities::previousPowerOfTwo(int x) +{ + if (isPowerOfTwo(x)) return x; + int n = 1; + x >>= 1; + while (x) { x >>= 1; n <<= 1; } + return n; +} + +int +MathUtilities::nearestPowerOfTwo(int x) +{ + if (isPowerOfTwo(x)) return x; + int n0 = previousPowerOfTwo(x), n1 = nearestPowerOfTwo(x); + if (x - n0 < n1 - x) return n0; + else return n1; +} +