Question

In C#, how can I convert a 64 bit ones complement number (represented as a long or ulong) to a signed two's complement long?

For reference, I'm trying to implement ULP-based double comparison using BitConverter.DoubleToInt64Bits().

Was it helpful?

Solution

In order to convert a one's complement to a two's complement, you'll need to check whether the number is positive or negative first.
Since the positive representation of a two's complement is equivalent to that of a one's complement, you will only need to perform conversion when your one's complement is negative.

The actual conversion is done by taking the absolute value of the one's complement, flipping all bits, then incrementing the result by one.

if (myLong >> 63 != 0) // The last bit is not 0, meaning myLong is negative
{
    myLong = (myLong & (long.MaxValue >> 1)); // sets the leading bit to 0, making myLong positive
    myLong = ~myLong + 1; // flips all bits and increments by 1
}
return myLong;


// One-liner alternative
return myLong >> 63 != 0 ? (~(myLong & (long.MaxValue >> 1))) + 1 : myLong;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top