Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex to float conversion

Tags:

c#

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?

like image 238
Ali_dotNet Avatar asked Oct 26 '11 13:10

Ali_dotNet


People also ask

How do you convert a floating number to hexadecimal?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.

Can you convert hex to decimal?

Solution: Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers.


2 Answers

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     
like image 112
Michael Fox Avatar answered Sep 29 '22 09:09

Michael Fox


Something like this:

        byte[] bytes = BitConverter.GetBytes(0x08fdc941);
        if (BitConverter.IsLittleEndian)
        {
            bytes = bytes.Reverse().ToArray();
        }
        float myFloat = BitConverter.ToSingle(bytes, 0);
like image 28
Simon Mourier Avatar answered Sep 29 '22 08:09

Simon Mourier