在c#中指定一个特定的双精度文字 [英] Specify a specific double precision literal in c#

查看:133
本文介绍了在c#中指定一个特定的双精度文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#中指定一个特定的 double 精确文字或值?

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

例如,我会喜欢在程序中使用不到一个最大的 double 值的常量。小于$ double 二进制是 1.11111111 11111111 11111111 11111111 11111111 11111111 1111 x 2 ^( - 1)将其表示为十进制中的大端双倍将是 0x3fe f ffff ffff ffff

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 不能在声明一个 const ,所以这不能用于替换文字值。

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

使用这个工具,我可以想出文字 9.99999999999999888977697537484E- 1 ,其结果完全相同。 BitConverter.ToString(BitConverter.GetBytes(9.999999999999888977697537484E-1))==FF-FF-FF-FF-FF-FF-EF-3F

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".

有没有其他方法可以将特定的 double 值转换为c#代码,而不是找到最接近的双重表示形式的十进制文字你想要双倍?

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?

推荐答案

这可能是过分的,但是死了,为什么不呢?

This is probably overkill, but damn, why not?

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

hello, reinterpret_cast<> 在C#

这篇关于在c#中指定一个特定的双精度文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆