I am currently trying to build a program which prints an input float value to binary.
The first bit is 0 if positive or 1 if negative, but with an input value of e.g.: -0.0g my if statement always prints 1, also for a positive input. How would I check that correctly?
string sign = "sign: ";
if(value <= -0.0f)
sign.append("1\n");
else if (value >= 0.0f)
sign.append("0\n");
...
CodePudding user response:
0.0 and -0.0 have the same value, yet different signs.
value <= -0.0f
is true for value
as 0.0 and -0.0. @MSalters
To distinguish the sign, use std::signbit()
. @john
if(std::signbit(value)) {
sign.append("1\n");
} else {
sign.append("0\n");
}
Note that signbit()
also applies to infinities and NaN.
Even though std::signbit reports "Along with std::copysign
, std::signbit
is one of the only two portable ways to examine the sign of a NaN.", there may be others.