Trouble converting to a specific format C#

63 views Asked by At

This may be a bit of a weird question, however I have made a program which communicates with another program (the other program was not made by me). I need to send 'distances' to the other program, however I am having trouble understanding how the program is interpreting these distances.

I have intercepted a device which successfully sends distances to the program. Below is an example of a distance being sent. I think the program reads in a distance as a ushort. Hopefully there'll be simple thing I am missing as I cannot seem to be able to convert my distances to the same format.

For example: Distance to be sent is 74. The bytes sent are [0, 74]. This as a ushort is 18944.

My initial thinking was the distance is converted ushort. Then the bytes of the ushort is sent to the program. However this doesn't seem to be the case.

1

There are 1 answers

3
Dmitry Bychenko On BEST ANSWER

It's Endianness that is the cause of the error:

  • sender: 74 (int16) == [0, 74] - first high, then low bytes
  • reciever: 74 (int16) == [74, 0] - first low, then high bytes

And that's why the reciever gets

   0 + 74 * 256 == 18944

Try checking Little/Big Endian (i.e. order of the bytes):

   byte[] data = new byte[] { 0, 74 };

   // If the WorkStation uses Little Endian order, we have to reverse the buffer
   ushort dist = BitConverter.ToUInt16(BitConverter.IsLittleEndian 
       ? data.Reverse().ToArray() 
       : data, 
     0);

   // 74
   Console.WriteLine(dist);