简体   繁体   English

十六进制到浮点数的转换

[英]hex to float conversion

I have a 4 byte hex number:我有一个 4 字节的十六进制数:

08fdc941

it should be convrted to a float number: 25.25, but I don't know how?它应该转换为浮点数:25.25,但我不知道如何? I use C#我使用 C#

what is the correct way of converting from hex to float?从十六进制转换为浮点数的正确方法是什么?

From this page on MSDN "How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide)".从 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     

Something like this:像这样的东西:

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

This yields 25.24855 , which is what I think you were looking for.这产生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;

For more information, see this:有关更多信息,请参阅此:

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

Are you sure it's the right way around, since BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0) is close.你确定这是正确的方法,因为BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0)很接近。

Edit:编辑:

Incidentally, http://en.wikipedia.org/wiki/Single_precision_floating-point_format gives a pretty good summary of how ISO/IEC/IEEE 60559 (IEEE 754) single-precision floating-point numbers work.顺便提一下, 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