5

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!

1
  • 3
    90 is an int, not a float. 90f is a float. In either case, whatever you're doing here is quite possibly the wrong thing to do -- occasionally there is a useful need for converting a float into bytes using BitConverter, but for most serialization purposes it's actually not the right tool. Commented Aug 26, 2019 at 13:53

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

Comments

6

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).

Comments

6

You need to change the input on the GetBytes, it's an integer now.

It's now getting the bytes on how the integer is stored and interpretate as how a float would be stored in memory.

Change it to a float.

Try:

byte[] b = BitConverter.GetBytes(90f);  // <-- add an f for floats.
Array.Reverse(b);
float fb = BitConverter.ToSingle(b, 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.