Boost logo

Boost :

From: Johan Råde (rade_at_[hidden])
Date: 2006-08-03 07:37:40


John Maddock wrote:

> And the endianness of the float's if you're doing bit testing. But of
> course if there is a macro already it's easy enough to convert it into a
> function.

The following function does bit testing, without advance knowledge of
which bit is the sign bit. The function figures out on its own, at
compile time, which bit is the sign bit. Hence you do not have to worry
about IEEE 754 and endianness. The only thing that is required is that
sizeof(float) == sizeof(int).

     bool signbit(float x)
     {
         const float one = 1;
         const float neg_one = -1;
         const int sign_mask = reinterpret_cast<const int&>(one)
            ^ reinterpret_cast<const int&>(neg_one);
         return reinterpret_cast<int&>(x) & sign_mask;
     }

I have tested it on VC++ 7.1 with signed zeroes, signed infinities and
signed NaNs, and plain signed numbers.

--Johan Råde


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk