有没有一种简单的方法在C#(或.NET)中从double类型中获取尾数和指数?我找到了这个例子,使用谷歌搜索(参考链接),但是我不确定它有多健壮。在将来的框架版本中,double的二进制表示是否会改变等?我找到的另一个选择是使用System.Decimal代替double,并使用Decimal.GetBits()方法来提取它们。有什么建议吗?
二进制格式不应该改变 - 这肯定会对现有规范造成破坏性影响。它被定义为IEEE754 / IEC 60559:1989格式,就像Jimmy所说的那样。(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++;
}
…
}
当时这些评论对我来说很有意义,但现在我肯定需要花一些时间去思考它们。在最初的部分之后,您可以获得“原始”的指数和尾数 - 其余代码只是帮助更简单地处理它们。
该表示法是IEEE标准,不应更改。
https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx
Double类型符合IEC 60559:1989(IEEE 754)二进制浮点算术标准。