简体   繁体   English

无法转换为特定格式C#

[英]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. 我认为该程序读取的距离为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]. 例如:要发送的距离是74.发送的字节是[0,74]。 This as a ushort is 18944. 这个作为ushort是18944。

My initial thinking was the distance is converted ushort. 我最初的想法是距离转换为ushort。 Then the bytes of the ushort is sent to the program. 然后将ushort的字节发送到程序。 However this doesn't seem to be the case. 然而,情况似乎并非如此。

It's Endianness that is the cause of the error: 这是导致错误的Endianness

  • sender: 74 (int16) == [0, 74] - first high, then low bytes sender: 74 (int16) == [0, 74] - 第一个高位,然后是低位字节
  • reciever: 74 (int16) == [74, 0] - first low, then high bytes 接收器: 74 (int16) == [74, 0] - 第一个低,然后是高字节

And that's why the reciever gets 这就是收货人得到的原因

   0 + 74 * 256 == 18944

Try checking Little/Big Endian (ie order of the bytes): 尝试检查Little / Big Endian (即字节的顺序 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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