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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With