提取尾数和指数的双用C# [英] extracting mantissa and exponent from double in c#
问题描述
有没有简单的方法来获得在C#中(一般或.NET)的尾数和指数从双?
Is there any straightforward way to get the mantissa and exponent from a double in c# (or .NET in general)?
我发现这个例子使用谷歌,但我不知道这将是多么强大的是。莫非二进制重新presentation的双重变化框架将来的某个版本,等等?
I found this example using google, but I'm not sure how robust it would be. Could the binary representation for a double change in some future version of the framework, etc?
我发现另一种方法是使用System.Decimal,而不是双并使用<一个href="http://msdn.microsoft.com/en-us/library/system.decimal.getbits(VS.80).aspx">Decimal.GetBits()方法来提取它们。
The other alternative I found was to use System.Decimal instead of double and use the Decimal.GetBits() method to extract them.
有什么建议?
推荐答案
二进制格式不应该改变 - 这肯定会是一个重大更改现有的规范。它的定义是在IEEE754 / IEC 60559:1989的格式,如吉米说。 (C#3.0语言规范第1.3节; ECMA 335第8.2.2节)。在code在DoubleConverter应罚款和强大。
The binary format shouldn't change - it would certainly be a breaking change to existing specifications. It's defined to be in IEEE754 / IEC 60559:1989 format, as Jimmy said. (C# 3.0 language spec section 1.3; ECMA 335 section 8.2.2). The code in DoubleConverter should be fine and robust.
有关为了将来参考,的code中的例子中的相关位是:
For the sake of future reference, the relevant bit of the code in the example is:
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 < 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 "0";
}
/* Normalize */
while((mantissa & 1) == 0)
{ /* i.e., Mantissa is even */
mantissa >>= 1;
exponent++;
}
…
}
的意见是有道理的,我的时间,但我敢肯定,我现在已经想了关于他们的一段时间。的第一部分之后,你已经得到了原始指数和尾数 - 的code只是帮助治疗他们在一个更简单的方式,其余
The comments made sense to me at the time, but I'm sure I'd have to think for a while about them now. After the very first part you've got the "raw" exponent and mantissa - the rest of the code just helps to treat them in a simpler fashion.
这篇关于提取尾数和指数的双用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!