Valerio
Valerio

Reputation: 131

Method BitConverter.DoubleToInt64Bits (Double) in C#

This method convert a double value into its bit representation formatted in hexadecimal format. Why is specified that the converted value is a signed int64 ? Which is the difference with unsigned int64 ? The binary representation of the double is unique.

Upvotes: 2

Views: 561

Answers (1)

Tim
Tim

Reputation: 6060

First off, that method does not convert it to hexadecimal, it converts the bits to be interpreted as an Int64, which you could then convert to a hexadecimal string if you chose, using ToString("X") or some such.

There is no difference between a signed Int64 and unsigned UInt64 under the hood-- the only difference is how the 64-bit word is interpreted by your program.

A 64-bit double is also a 64-bit word, under the hood-- but some processors, like intel x86 family of processors, support an 80-bit double precision floating point, not just a 64-bit double. That method is simply allowing C# to interpret the bits for a 64-bit double (or convert an 80-bit double to a 64-bit double, if that's what it has to work with) as if it were a 64-bit signed int. If you want to interpret that as a 64-bit unsigned int, just cast it (using unchecked to prevent c# from freaking out):

ulong bitsForDouble;
unchecked {
    bitsForDouble = (ulong)BitConverter.DoubleToInt64Bits(someDoubleValue);
}

It doesn't make sense to interpret the bits of a double as either an Int64 or a UInt64-- they just wanted to give us a way to represent a double in a 64-bit value for whatever bit manipulation needs we might have.

Upvotes: 3

Related Questions