problem converting 4-bytes array to float in C#
Your bytes are coming out word-swapped. This function should convert your byte array to floats properly:
static float ToFloat(byte[] input){ byte[] newArray = new[] { input[2], input[3], input[0], input[1] }; return BitConverter.ToSingle(newArray, 0);}ToFloat(new byte[]{2,73,98,43}) == 533174.1
- How about endianess? Have you tried reversing the word order? In windows, 533174.1 is 98, 43, 2, 73.
- 4 bytes are a single (ToSingle), not double.
To convert a byte array with four positions to float, Convert.ToSingle should be used, this function reads four positions within the array used, for example:
var input = new byte[]{103, 242, 50, 67};var floatValue = BitConverter.ToSingle(input, 0);
floatValue = 178.946884
The Convert.ToSingle method receives two parameters: the byte array and the position where it will start taking the values.
We can also take an array with greater length and define where to start the conversions
var secondInput = new byte[]{103, 242, 50, 67, 227, 55, 179, 67};var firtsFloatValue = BitConverter.ToSingle(input, 0);var secondFloatValue = BitConverter.ToSingle(input, 4);
firtsFloatValue = 178.946884
secondFloatValue = 358.4366
Finally to obtain the value 533174.1 starting from [98, 43, 2, 73] we must use
var input = new byte[]{98, 43, 2, 73};var floatValue = BitConverter.ToSingle(input, 0);
floatValue = 533174.1