Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array to float

I am trying to cast a float into a byte array of length 4, and then back again. But I it doesn's seems to work.

Here's what I've done:

byte[] b = BitConverter.GetBytes(90);
float fb = BitConverter.ToSingle(b, 0);

I expected fb = 90, but it's 1.26E-43.

I know that my converter is little endian, so I've also tried to reverse the array, like this:

byte[] b = BitConverter.GetBytes(90);
Array.Reverse(b);
float fb = BitConverter.ToSingle(b, 0);

Then I got the answer fb = 9.0E+15.

Any ideas? Thanks in advance!

like image 772
random Avatar asked Aug 26 '19 13:08

random


2 Answers

BitConverter.GetBytes(90); will give you the bytes for the integer value of 90. Since you want the bytes for the float value, you need to specify that:

BitConverter.GetBytes((float)90.0);

or

BitConverter.GetBytes(90.0f);
like image 124
D Stanley Avatar answered Sep 24 '22 20:09

D Stanley


90 is a literal that is interpreted by the compiler as Int32, not as Single. So you call the wrong overload of GetBytes().

Use: byte[] b = BitConverter.GetBytes(90f);

to tell the compiler you want to call GetBytes(float).

like image 30
René Vogt Avatar answered Sep 26 '22 20:09

René Vogt