dve*_*ema 26 .net c# floating-point
有没有直接的方法从c#(或一般的.NET)中获取双尾数和指数?
我发现这个使用谷歌的例子,但我不确定它会有多强大.二进制表示可以在框架的某些未来版本中进行双重更改吗?
我发现的另一个替代方法是使用System.Decimal而不是double,并使用Decimal.GetBits()方法来提取它们.
有什么建议?
Jon*_*eet 28
二进制格式不应该改变 - 它肯定会对现有规范进行重大改变.吉米说,它被定义为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++;
}
…
}
Run Code Online (Sandbox Code Playgroud)
这些评论在当时对我有意义,但我相信我现在必须考虑一下.在第一部分之后,您已经获得了"原始"指数和尾数 - 其余代码只是有助于以更简单的方式对待它们.