From 52300cf40252566a083c9495029133f520d3a4a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Sat, 12 Jan 2013 18:24:39 +0100 Subject: [PATCH] Math: function for base-2 logarithm. Verbatim copy from Corrade, might be better to have it here too (possibly some SIMD optimizations?). --- src/Math/Math.cpp | 7 +++++++ src/Math/Math.h | 9 +++++++++ src/Math/Test/MathTest.cpp | 8 +++++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Math/Math.cpp b/src/Math/Math.cpp index 7e432040f..d2cdd0ce6 100644 --- a/src/Math/Math.cpp +++ b/src/Math/Math.cpp @@ -17,6 +17,13 @@ namespace Magnum { namespace Math { +std::uint32_t log2(std::uint32_t number) { + std::uint32_t log = 0; + while(number >>= 1) + ++log; + return log; +} + std::uint32_t log(std::uint32_t base, std::uint32_t number) { std::uint32_t log = 0; while(number /= base) diff --git a/src/Math/Math.h b/src/Math/Math.h index 9bc03cf82..7a9004fe1 100644 --- a/src/Math/Math.h +++ b/src/Math/Math.h @@ -58,10 +58,19 @@ template inline constexpr T pow(T base) { return Implementation::Pow()(base); } +/** + * @brief Base-2 integral logarithm + * + * Returns integral logarithm of given number with base `2`. + * @see log() + */ +std::uint32_t MAGNUM_EXPORT log2(std::uint32_t number); + /** * @brief Integral logarithm * * Returns integral logarithm of given number with given base. + * @see log2() */ std::uint32_t MAGNUM_EXPORT log(std::uint32_t base, std::uint32_t number); diff --git a/src/Math/Test/MathTest.cpp b/src/Math/Test/MathTest.cpp index e14aeaf18..044bfa350 100644 --- a/src/Math/Test/MathTest.cpp +++ b/src/Math/Test/MathTest.cpp @@ -28,6 +28,7 @@ class MathTest: public Corrade::TestSuite::Tester { void clamp(); void pow(); void log(); + void log2(); }; MathTest::MathTest() { @@ -35,7 +36,8 @@ MathTest::MathTest() { &MathTest::denormalize, &MathTest::clamp, &MathTest::pow, - &MathTest::log); + &MathTest::log, + &MathTest::log2); } void MathTest::normalize() { @@ -105,6 +107,10 @@ void MathTest::log() { CORRADE_COMPARE(Math::log(256, 2), 0ul); } +void MathTest::log2() { + CORRADE_COMPARE(Math::log2(2153), 11); +} + }}} CORRADE_TEST_MAIN(Magnum::Math::Test::MathTest)