Boost logo

Boost :

From: Johan Råde (rade_at_[hidden])
Date: 2006-08-04 07:29:51


Here is a new version of signbit, taking input from Peter Dimov into
account:

template<class T, class S> T binary_cast(const S& s)
{
     BOOST_STATIC_ASSERT(sizeof(S) == sizeof(T));
     T t;
     memcpy(&t, &s, sizeof(S));
     return t;
}

const boost::uint32_t signbit_mask
     = binary_cast<boost::uint32_t>(1.0f)
     ^ binary_cast<boost::uint32_t>(-1.0f);

inline bool signbit(float x)
{
     return binary_cast<boost::uint32_t>(x) & signbit_mask;
}

inline bool signbit(double x)
{
     return signbit(static_cast<float>(x));
}

inline bool signbit(long double x)
{
     return signbit(static_cast<float>(x));
}

The code should work on any platform with
1. IEEE 754 or some similar representation
2. sizeof(float) == 4
3. casts between different numeric types preserve the sign bit,
also for non-finite numbers.

The function is intended to be used when there is no predefined
signbit function or macro.

--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