Fast sign in C++ float...are there any platform dependencies in this code?
- by Patrick Niedzielski
Searching online, I have found the following routine for calculating the sign of a float in IEEE format. This could easily be extended to a double, too.
// returns 1.0f for positive floats, -1.0f for negative floats, 0.0f for zero
inline float fast_sign(float f) {
if (((int&)f & 0x7FFFFFFF)==0) return 0.f; // test exponent & mantissa bits: is input zero?
else {
float r = 1.0f;
(int&)r |= ((int&)f & 0x80000000); // mask sign bit in f, set it in r if necessary
return r;
}
}
(Source: ``Fast sign for 32 bit floats'', Peter Schoffhauzer)
I am weary to use this routine, though, because of the bit binary operations. I need my code to work on machines with different byte orders, but I am not sure how much of this the IEEE standard specifies, as I couldn't find the most recent version, published this year. Can someone tell me if this will work, regardless of the byte order of the machine?
Thanks,
Patrick