problem converting 4-bytes array to float in C#

14,425

Solution 1

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

Solution 2

  1. How about endianess? Have you tried reversing the word order? In windows, 533174.1 is 98, 43, 2, 73.
  2. 4 bytes are a single (ToSingle), not double.
Share:
14,425
Igal
Author by

Igal

"We don't have bugs in our software.Only features" (my boss).

Updated on July 29, 2022

Comments

  • Igal
    Igal almost 2 years

    I'm using C# and reading bytes array from some controller and converting them to their types. all values (int,string) OK except the float values. The value that suppose to get is 533174.1. but when reading the array

    byteArr[0]=2
    byteArr[1]=73
    byteArr[2]=98
    byteArr[3]=43
    

    getting some gibberish value. I used the System.BitConverter.ToDouble(bytesArr,0) and other methods without success. please help. Thanks, Igal.