c++floating-pointsignedness

Sign of a floating point number


Is there an easy way to determine the sign of a floating point number?

I experimented and came up with this:

#include <iostream>

int main(int argc, char** argv)
{
 union
 {
  float f;
  char c[4];
 };

 f = -0.0f;
 std::cout << (c[3] & 0x10000000) << "\n";

 std::cin.ignore();
 std::cin.get();
 return 0;
}

where (c[3] & 0x10000000) gives a value > 0 for a negative number but I think this requires me to make the assumptions that:

Please correct me if any of those assumptions are wrong or if I have missed any.


Solution

  • Assuming it's a valid floating point number (and not, for example, NaN):

    float f;
    bool is_negative = f < 0;
    

    It is left as an exercise to the reader to figure out how to test whether a floating point number is positive.