Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem converting 4-bytes array to float in C#

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.

like image 944
Igal Avatar asked Nov 29 '10 07:11

Igal


People also ask

Is float always 4 bytes?

Yes it has 4 bytes only but it is not guaranteed.

Why size of float is 4 bytes?

The size of a float or other data types for that matter is dependent upon the system. It has to do with the hardware architecture and the compiler. This float, 10498.429 , would also be 4 bytes in memory. If a given computer system had a float size of 4 bytes then all floats are 4 bytes.


2 Answers

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
like image 103
Gabe Avatar answered Oct 23 '22 03:10

Gabe


  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.
like image 27
Yodan Tauber Avatar answered Oct 23 '22 02:10

Yodan Tauber