Search code examples
c#arraysbitconverter

Float to Byte array in other format


I'm using Bitconverter to convert from a float to a Byte array.

byte[] ValueByteArray = BitConverter.GetBytes(Value);

Now I'm evaluating my application with another application, and the goal is of course that my output is exactly the same. Problem is, it isn't.

I'm 100% sure the test output is correct, and my value is 'wrong' or in another format. Because in a client, connected to the reference application, the value is 5.5 and mine is 6.09414613e-039

My application:

  • Test value: 5,5
  • Byte array value: 0.0.5C.42
  • Value in client application: 6.09414613e-039

Reference application:

  • Test value: 5,5
  • Byte array value: 0.0.B0.40
  • Value in client application: 5,5

Solution

  • Your reference application is correct; 0x00005C42 is 55, not 5.5; this may be as simple as comma vs period as the decimal specifier in some of your parse code. The 6.09414613e-039 appears to be an off-by-one error in the byte order (see bottom row)

    Examples:

    float value = 5.5F;
    var bytes = BitConverter.GetBytes(value);
    Console.WriteLine(BitConverter.ToString(bytes)); // 00-00-B0-40
    

    and

    float value = 55;
    var bytes = BitConverter.GetBytes(value);
    Console.WriteLine(BitConverter.ToString(bytes)); // 00-00-5C-42
    

    and

    float value = 6.09414613e-039F;
    var bytes = BitConverter.GetBytes(value);
    Console.WriteLine(BitConverter.ToString(bytes)); // 00-5C-42-00