C#变为实数 [英] C# double to real

查看:273
本文介绍了C#变为实数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将double转换为pascal real,但是当我将0.23转换为real时,我却得到0.23999999 real,我如何将所有9999截断为0000。

i am trying to convert double to pascal real but when i convert 0.23 to real i got 0.23999999 real how can i truncate all 9999 to 0000.

public static byte[] Double2Real48(double d)
{
    byte[] r48 = new byte[6];
    byte[] da = BitConverter.GetBytes(d);

    for (int i = 0; i < r48.Length; i++)
        r48[i] = 0;

    //Copy the negative flag
    r48[5] |= (byte)(da[7] & 0x80);

    //Get the expoent
    byte b1 = (byte)(da[7] & 0x7f);
    ushort n = (ushort)(b1 << 4);
    byte b2 = (byte)(da[6] & 0xf0);
    b2 >>= 4;
    n |= b2;

    if (n == 0)
        return r48;

    byte ex = (byte)(n - 1023);
    r48[0] = (byte)(ex + 129);

    //Copy the Mantissa
    r48[5] |= (byte)((da[6] & 0x0f) << 3);//Get the last four bits
    r48[5] |= (byte)((da[5] & 0xe0) >> 5);//Get the first three bits

    r48[4] = (byte)((da[5] & 0x1f) << 3);//Get the last 5 bits
    r48[4] |= (byte)((da[4] & 0xe0) >> 5);//Get the first three bits

    r48[3] = (byte)((da[4] & 0x1f) << 3);//Get the last 5 bits
    r48[3] |= (byte)((da[3] & 0xe0) >> 5);//Get the first three bits

    r48[2] = (byte)((da[3] & 0x1f) << 3);//Get the last 5 bits
    r48[2] |= (byte)((da[2] & 0xe0) >> 5);//Get the first three bits

    r48[1] = (byte)((da[2] & 0x1f) << 3);//Get the last 5 bits
    r48[1] |= (byte)((da[1] & 0xe0) >> 5);//Get the first three bits

    return r48;

}


推荐答案

我的转换程序。请注意,我在这里未对处理IEEE无限性或NaN值做任何特殊说明。

Here are my conversion routines. Note that I haven't put anything special here for treating IEEE infinities or NaN values.

static byte[] DoubleToReal48(double d)
{
    byte[] r = new byte[6];

    long bits = BitConverter.DoubleToInt64Bits(d);
    bool negative = ((bits >> 63) & 1) != 0;
    long exponent = ((bits >> 52) & 0x7FF) - 1023;
    long mantissa = bits & 0xFFFFFFFFFFFFFL;

    long raw = (negative ? 1 : 0);
    raw = (raw << 39) | (mantissa >> 13);
    raw = (raw << 8) | ((exponent + 129) & 0xFF);

    for (int k = 0; k < 6; k++)
    {
        r[k] = (byte)(raw & 0xFF);
        raw >>= 8;
    }
    return r;
}

static double Real48ToDouble(byte[] r)
{
    long raw = 0;
    for (int k = 5; k >= 0; k--)
    {
        raw = (raw << 8) | r[k];
    }

    long mantissa = (raw << 5) & 0xFFFFFFFFFD000L;
    long exponent = (((raw & 0xFF) - 129 + 1023) & 0x7FF) << 52;
    long sign = (((raw & ~0x7FFFFFFFFFFFL) != 0) ? 1 : 0) << 63;

    return BitConverter.Int64BitsToDouble(sign | exponent | mantissa);
}

往返转换会损失一些精度,但结果基本上是正确的。 [Real48ToDouble(DoubleToReal48(0.23))返回0.229999999999563]

There is some loss of precision with roundtrip conversions, but the results are basically correct. [Real48ToDouble(DoubleToReal48(0.23)) returns 0.229999999999563]

这篇关于C#变为实数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆