[英]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;
有關更多信息,請參閱此:
你確定這是正確的方法,因為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.