Specify a specific double precision literal in c#

拜拜、爱过 提交于 2019-12-13 16:06:55

问题


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#



来源:https://stackoverflow.com/questions/24420086/specify-a-specific-double-precision-literal-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!