Specify a specific double precision literal in c#

2019-07-23 09:14发布

问题:

How can I specify a specific double precision literal or value in c#?

For example, I would like to use the constant of the largest double value less than one in a program. The largest double less than one is 1.11111111 11111111 11111111 11111111 11111111 11111111 1111 x 2^(-1) in binary. Expressing this as a big-endian double in hex would be 0x3fe f ffff ffff ffff

I can generate it with the following code:

var largestDoubleLessThanOneBytes = new byte[] {0x3f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
if (BitConverter.IsLittleEndian) largestDoubleLessThanOneBytes = largestDoubleLessThanOneBytes.Reverse().ToArray();
double largestDoubleLessThanOne = BitConverter.ToDouble(largestDoubleLessThanOneBytes, 0);

BitConverter can't be used in the declaration of a const, so this can't be used in place of a literal value.

Using this tool, I can come up with the literal 9.99999999999999888977697537484E-1, which ends up being exactly the same double. BitConverter.ToString(BitConverter.GetBytes(9.99999999999999888977697537484E-1)) == "FF-FF-FF-FF-FF-FF-EF-3F".

Is there any other way to get specific double values into c# code than to find a decimal literal whose closest double representation is the double you want?

回答1:

This is probably overkill, but damn, why not?

unsafe
{
    var x = 0x3fefffffffffffff;
    var d = *(double*)&x;
    Console.WriteLine("{0:r}", d);
}

hello, reinterpret_cast<> in C#



标签: c# double