Mercurial > hg > qm-dsp
diff maths/MathUtilities.cpp @ 280:9c403afdd9e9
* Various fixes related to the bar estimator code
author | Chris Cannam <c.cannam@qmul.ac.uk> |
---|---|
date | Tue, 10 Feb 2009 16:37:11 +0000 |
parents | c8908cdc8c32 |
children | 5e125f030287 |
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; +} +