简体   繁体   中英

hex to float conversion

I have a 4 byte hex number:

08fdc941

it should be convrted to a float number: 25.25, but I don't know how? I use 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)".

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.

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

Are you sure it's the right way around, since BitConverter.ToSingle(BitConverter.GetBytes(0x08fdc941).Reverse().ToArray(), 0) is close.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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