c# - 从c#中的double中提取尾数和指数

标签 c# .net floating-point

有没有直接的方法从 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/

相关文章:

c# - 如何在C#中逐点绘制形状?

c# - DI Autofac 中的 RegisterInstance 和 RegisterType 有什么区别

c# - 查找包含闭包/lambda 的函数的属性

scala - 为什么 0.29999999999999998 转换为 0.3?

c# - 将一个线程的结果通知另一个线程或等待第一个线程的反馈以继续第二个线程

c# - 再锐化。为什么要转换为汽车属性(property)?

c# - 单选按钮作为一组在不同的面板中

c# - 对 I/O 绑定(bind)操作使用异步函数

java - 在 Java 中,如何测试 `Double` 列表是否包含特定值

c++ - 在比较 float 时使用 epsilon 是否会破坏严格弱排序?