1

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");

...

A02
  • 43
  • 4
  • 4
    Simple method, use the [signbit](https://en.cppreference.com/w/cpp/numeric/math/signbit) function. – john Nov 22 '22 at 12:40
  • 2
    [`std::signbit` on cppreference](https://en.cppreference.com/w/cpp/numeric/math/signbit) – kotatsuyaki Nov 22 '22 at 12:40
  • Note that, in IEEE 754, negative zero is a valid value. – ChrisMM Nov 22 '22 at 12:44
  • 3
    @ChrisMM: More importantly, in IEEE754 positive and negative zero are _equal_. That's why the code fails `+0.0f <= -0.0f` is true, because `+0.0f == -0.0f` – MSalters Nov 22 '22 at 13:59

1 Answers1

1

+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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256