Converting 2 bytes to Short in C#

前端 未结 3 509
清歌不尽
清歌不尽 2020-12-03 20:58

I\'m trying to convert two bytes into an unsigned short so I can retrieve the actual server port value. I\'m basing it off from this protocol specification under Reply Forma

3条回答
  •  借酒劲吻你
    2020-12-03 21:14

    If you reverse the values in the BitConverter call, you should get the expected result:

    int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);
    

    On a little-endian architecture, the low order byte needs to be second in the array. And as lasseespeholt points out in the comments, you would need to reverse the order on a big-endian architecture. That could be checked with the BitConverter.IsLittleEndian property. Or it might be a better solution overall to use IPAddress.HostToNetworkOrder (convert the value first and then call that method to put the bytes in the correct order regardless of the endianness).

提交回复
热议问题