十六进制到浮点转换

Ali*_*Net 6 c#

我有一个4字节的十六进制数:

08fdc941
Run Code Online (Sandbox Code Playgroud)

它应该是一个浮点数:25.25,但我不知道如何?我用C#

从十六进制转换为浮点数的正确方法是什么?

Mic*_*Fox 7

从MSDN上的这个页面"如何:在十六进制字符串和数字类型之间转换(C#编程指南)".

string hexString = "43480170";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);

byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);

// Output: 200.0056     
Run Code Online (Sandbox Code Playgroud)


Sim*_*ier 5

像这样:

        byte[] bytes = BitConverter.GetBytes(0x08fdc941);
        if (BitConverter.IsLittleEndian)
        {
            bytes = bytes.Reverse().ToArray();
        }
        float myFloat = BitConverter.ToSingle(bytes, 0);
Run Code Online (Sandbox Code Playgroud)

  • 字节序将通过第一个GetBytes解决。您不需要`BitConverter.IsLittleEndian`。 (2认同)