What is the C# equivalent for C++
bool std::signbit( double arg );
The C++ reference description of this function is as follows: Determines if the given floating point number arg is negative. This function detects the sign bit of zeroes, infinities, and NaNs. Along with std::copysign, this macro is one of the only two portable ways to examine the sign of a NaN.
signbit(+0.0) = false
signbit(-0.0) = true
I'm not sure whether there is a builtin, but this should work:
private static readonly long SignMask = BitConverter.DoubleToInt64Bits(-0.0) ^
BitConverter.DoubleToInt64Bits(+0.0);
public static bool signbit(double arg)
{
return (BitConverter.DoubleToInt64Bits(arg) & SignMask) == SignMask;
}
Based on this answer by Jon Skeet.
Reverse-engineered from the machine code in the Microsoft CRT, keeping it fast:
public unsafe static bool stdsign(double d) {
ushort* pd = (ushort*)&d;
return (pd[3] & 0x8000) != 0;
}
Passes all the tests that I know how to throw at it. Little-endian architecture assumed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With