Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the sign-bit of a double?

Tags:

c#

std

double

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
like image 996
Sebastian Widz Avatar asked Oct 22 '25 03:10

Sebastian Widz


2 Answers

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.

like image 90
Deduplicator Avatar answered Oct 25 '25 02:10

Deduplicator


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.

like image 29
Hans Passant Avatar answered Oct 25 '25 04:10

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!