有没有直接的方法从 c#(或一般的 .NET)中的 double 中获取尾数和指数?
我找到了 this example使用谷歌,但我不确定它会有多强大。是否可以在某些 future 版本的框架等中更改双重的二进制表示?
我发现的另一种选择是使用 System.Decimal 而不是 double 并使用 Decimal.GetBits()提取它们的方法。
有什么建议吗?
最佳答案
二进制格式不应该改变——这肯定是对现有规范的重大改变。正如吉米所说,它被定义为 IEEE754/IEC 60559:1989 格式。 (C# 3.0 语言规范第 1.3 节;ECMA 335 第 8.2.2 节)。 DoubleConverter 中的代码应该很好且健壮。
为了将来引用,示例中的相关代码是:
public static string ToExactString (double d)
{
…
// Translate the double into sign, exponent and mantissa.
long bits = BitConverter.DoubleToInt64Bits(d);
// Note that the shift is sign-extended, hence the test against -1 not 1
bool negative = (bits & (1L << 63)) != 0;
int exponent = (int) ((bits >> 52) & 0x7ffL);
long mantissa = bits & 0xfffffffffffffL;
// Subnormal numbers; exponent is effectively one higher,
// but there's no extra normalisation bit in the mantissa
if (exponent==0)
{
exponent++;
}
// Normal numbers; leave exponent as it is but add extra
// bit to the front of the mantissa
else
{
mantissa = mantissa | (1L << 52);
}
// Bias the exponent. It's actually biased by 1023, but we're
// treating the mantissa as m.0 rather than 0.m, so we need
// to subtract another 52 from it.
exponent -= 1075;
if (mantissa == 0)
{
return negative ? "-0" : "0";
}
/* Normalize */
while((mantissa & 1) == 0)
{ /* i.e., Mantissa is even */
mantissa >>= 1;
exponent++;
}
…
}
当时这些评论对我来说很有意义,但我确信我现在必须考虑一下。在第一部分之后,您将获得“原始”指数和尾数 - 其余代码只是帮助以更简单的方式处理它们。
关于c# - 从c#中的double中提取尾数和指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/389993/