繁体   English   中英

十六进制到浮点数的转换

[英]hex to float conversion

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

08fdc941

它应该转换为浮点数:25.25,但我不知道如何? 我使用 C#

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

从 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     

像这样的东西:

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

这产生25.24855 ,这就是我认为你正在寻找的。

var bytes = BitConverter.GetBytes(0x08fdc941);
Array.Reverse(bytes);
var result = BitConverter.ToSingle(bytes, 0);
string hexString = 08fdc941;
Int32 IntRep = Int32.Parse(hexString, NumberStyles.AllowHexSpecifier);
// Integer to Byte[] and presenting it for float conversion
float myFloat = BitConverter.ToSingle(BitConverter.GetBytes(IntRep), 0);
// There you go
return myFloat;

有关更多信息,请参阅此:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types

你确定这是正确的方法,因为BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0)很接近。

编辑:

顺便提一下, http://en.wikipedia.org/wiki/Single_precision_floating-point_format很好地总结了 ISO/IEC/IEEE 60559 (IEEE 754) 单精度浮点数的工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM