
Paul A Bristow wrote:
Does anyone have a ***portable*** version of macro signbit (C99)
or can we combine versions that work on each compiler/hardware/endian...
or an equivalent C++ function, perhaps called is_negative?
(This would just test the signbit for the type(s)).
There are several places where this would be useful in dealing properly with NaNs and zero and infinity etc.
Or how about this template<class T> bool is_negative(const T& x) { return x < T(0); } template<> bool is_negative(const float& x) { const float one = 1; const float neg_one = -1; const int one_bits = reinterpret_cast<const int&>(one); const int neg_one_bits = reinterpret_cast<const int&>(neg_one); const int sign_mask = one_bits ^ neg_one_bits; return reinterpret_cast<const int&>(x) & sign_mask; } template<> bool is_negative(const double& x) { return is_negative(static_cast<float>(x)); } template<> bool is_negative(const long double& x) { return is_negative(static_cast<float>(x)); } --Johan Råde