2

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
Belekz
  • 480
  • 1
  • 7
  • 18
  • 3
    `BitConverter.ToString(BitConverter.GetBytes(5.5f))` is `00-00-B0-40`. Take a close look at what `Value` actually is. – Jeroen Mostert Feb 07 '18 at 13:01
  • 1
    When you are using `BitConverter` to produce data that will be shared across different machines, make sure to keep `BitConverter.IsLittleEndian` in mind. You don't want your application to produce results that depend on the used architecture. (Not relevant to the question itself, but I thought I'd point out a potential pitfall) – Manfred Radlwimmer Feb 07 '18 at 13:07

1 Answers1

4

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
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900