Reputation: 1562
I have tried the below C# code to convert from hex literal to floating point and get the correct result. I wish to input a byte array instead and have that converted to floating point but can't seem to get it right result.
0x4229ec00
is the current format. I need it in byte array
format something like...
new byte[]{ 0x01, 0x04, 0x01, 0x60, 0x00, 0x02, 0x70, 0x29}; //current output 42.48
The code looks like:
byte[] bytes = BitConverter.GetBytes(0x4229ec00);
float myFloat = floatConversion(bytes);
public float floatConversion(byte[] bytes)
{
float myFloat = BitConverter.ToSingle(bytes, 0);
return myFloat;
}
Any help would be greatly appreciated. Thank you!
Upvotes: 3
Views: 12241
Reputation: 186833
float (Single
) is a 4 Byte value;
Your test value 0x4229ec00 contains 4 bytes, they are: 0x42, 0x29, 0xEC, 0x00
x86 CPUs use reversed order of bytes (Little Endian), so the right byte array is
0x00, 0xEC, 0x29, 0x42
The Code
// Original array
Byte[] data = new Byte[] {0x42, 0x29, 0xEC, 0x00};
// 42.48047
// If CPU uses Little Endian, we should reverse the data
float result = BitConverter.ToSingle(BitConverter.IsLittleEndian? data.Reverse().ToArray() : data, 0);
Upvotes: 2
Reputation: 2234
You can amend your float conversion function as below
public float floatConversion(byte[] bytes)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes); // Convert big endian to little endian
}
float myFloat = BitConverter.ToSingle(bytes, 0);
return myFloat;
}
Upvotes: 7