IEEE754到浮点C#

时间:2015-06-23 11:52:02

标签: c# ieee-754

下面的代码很简单,从传递给函数的对象转换32位整数,32位整数代表浮点数。我已经通过在线计算器检查了我正在以正确的方式获得标志,指数和mantessa,但奇怪的是我得到了错误的答案。

任何人都可以检查我是否在数学上(或者可能是编程方式)以某种方式做错了吗?

此致

public double FromFloatSafe(object f)
    {
        uint fb = Convert.ToUInt32(f);


        uint sign, exponent = 0, mantessa = 0;
        uint bias = 127;

        sign = (fb >> 31) & 1;
        exponent = (fb >> 23) & 0xFF;
        mantessa = (fb & 0x7FFFFF);
        double fSign = Math.Pow((-1), sign);
        double fMantessa = 1 + (1 / mantessa);
        double fExponent = Math.Pow(2, (exponent -bias));
        double ret = fSign * fMantessa * fExponent;
        return ret;
    }

2 个答案:

答案 0 :(得分:2)

类似的东西:

  uint fb = Convert.ToUInt32(f);

  return BitConverter.ToSingle(BitConverter.GetBytes((int) fb), 0);

答案 1 :(得分:2)

这甚至可以处理非正规数字:

public static float FromFloatSafe(object f)
{
    uint fb = Convert.ToUInt32(f);

    int sign = (int)((fb >> 31) & 1);
    int exponent = (int)((fb >> 23) & 0xFF);
    int mantissa = (int)(fb & 0x7FFFFF);

    float fMantissa;
    float fSign = sign == 0 ? 1.0f : -1.0f;

    if (exponent != 0)
    {
        exponent -= 127;
        fMantissa = 1.0f + (mantissa / (float)0x800000);
    }
    else
    {
        if (mantissa != 0)
        {
            // denormal
            exponent -= 126;
            fMantissa = 1.0f / (float)0x800000;
        }
        else
        {
            // +0 and -0 cases
            fMantissa = 0;
        }
    }

    float fExponent = (float)Math.Pow(2.0, exponent);
    float ret = fSign * fMantissa * fExponent;
    return ret;
}

请注意,我确实认为这里有一些可疑的东西,但你要求它,我写了 ...我觉得这是XY problem

啊......请注意,虽然在学术上我写的很有趣,但我通常这样做:

[StructLayout(LayoutKind.Explicit)]
public struct UInt32ToFloat
{
    [FieldOffset(0)]
    public uint UInt32;

    [FieldOffset(0)]
    public float Single;
}

然后

float f = new UInt32ToFloat { UInt32 = Convert.ToUInt32(f) }.Single;