Sign of a floating point number

2019-02-12 14:38发布

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:

  • The machine's bytes are 8 bits big
  • a float point number is 4 bytes big?
  • the machine's most significant bit is the left-most bit (endianness?)

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

8条回答
Root(大扎)
2楼-- · 2019-02-12 15:43

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.

查看更多
The star\"
3楼-- · 2019-02-12 15:43

google the floating point format for your system. Many use IEEE 754 and there is specific sign bit in the data to examine. 1 is negative 0 is positive. Other formats have something similar, and as easy to examine.

Note trying to get the compiler to exactly give you the number you want with a hard coded assignment like f = -0.0F; may not work. has nothing to do with the floating point format but has to do with the parser and the C/C++ library used by the compiler. Generating a minus zero may or may not be that trivial in general.

查看更多
登录 后发表回答