简体   繁体   中英

Trouble converting to a specific format C#

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.

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 (ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM