hex到浮点转换
我有一个4字节的hex数:
08fdc941
它应该是一个浮点数:25.25,但我不知道如何? 我用C#
从hex转换为浮点数的正确方法是什么?
像这样的东西:
byte[] bytes = BitConverter.GetBytes(0x08fdc941); if (BitConverter.IsLittleEndian) { bytes = bytes.Reverse().ToArray(); } float myFloat = BitConverter.ToSingle(bytes, 0);
从MSDN上的这个页面“如何:在hex字符串和数字类型之间转换(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
这产生25.24855
,这是我认为你正在寻找的。
var bytes = BitConverter.GetBytes(0x08fdc941); Array.Reverse(bytes); var result = BitConverter.ToSingle(bytes, 0);
你确定它是正确的方法,因为BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0)
是关闭的。
编辑:
顺便提一下, http://en.wikipedia.org/wiki/Single_precision_floating-point_format给出了ISO / IEC / IEEE 60559(IEEE 754)单精度浮点数如何工作的非常好的总结。