简体   繁体   中英

C# convert one's complement bits to a two's complement long?

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() .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM