From 757b73238e00e4a0ccacb889e268d2fd0e35d030 Mon Sep 17 00:00:00 2001 From: Vitor Fernandes Date: Thu, 16 Jul 2020 01:20:12 +0100 Subject: [PATCH] Fix msb2 --- src/bmath/demos/math.cpp | 5 +++-- src/bmath/math.cpp | 11 +++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/bmath/demos/math.cpp b/src/bmath/demos/math.cpp index f593012..77c2e62 100644 --- a/src/bmath/demos/math.cpp +++ b/src/bmath/demos/math.cpp @@ -8,10 +8,11 @@ int main(void) Int a = -12; Float b = -12.0f; - Int c=3; + Int c=-3; Int d=4; std::cout << "A: " << a << ", abs(A): " << Math::abs(a) << std::endl; std::cout << "B: " << b << ", abs(B): " << Math::abs(b) << std::endl; - std::cout << "MAX(C,D)=(" << c << ", " << d << "), max(C,D): " << Math::max(c,d) << std::endl; + std::cout << "MAX(C,D)=(" << c << ", " << d << "), max(C,D): " << Math::max(d,c) << std::endl; + std::cout << "MIN(C,D)=(" << c << ", " << d << "), min(C,D): " << Math::min(c,d) << std::endl; } diff --git a/src/bmath/math.cpp b/src/bmath/math.cpp index e389d62..f4afbee 100644 --- a/src/bmath/math.cpp +++ b/src/bmath/math.cpp @@ -1,6 +1,7 @@ #include "math.hpp" //http://graphics.stanford.edu/~seander/bithacks.html +//https://hbfs.wordpress.com/2008/08/05/branchless-equivalents-of-simple-functions/ //access CHAR_BIT --> const with number of bits in a byte (usually 8) #include #include @@ -32,7 +33,7 @@ inline Int msb2(Int value) } SInt; SInt sint = {.sint = value}; - return sint.sint; + return sint.int_with_msb.signal; }; /** @@ -50,8 +51,14 @@ Float BMath::Math::abs(Float value) return value > 0 ? value : -value; }; +template <> +Int BMath::Math::min(Int a,Int b) +{ + return b + ((a-b) & msb2(a-b)); +} + template <> Int BMath::Math::max(Int a,Int b) { - return (a-b) & msb2(a-b); + return a + ((b-a) & ~msb2(b-a)); }