Converting 2 bytes to Short in C#

前端 未结 3 513
清歌不尽
清歌不尽 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:33

    BitConverter is doing the right thing, you just have low-byte and high-byte mixed up - you can verify using a bitshift manually:

    byte port1 = 105;
    byte port2 = 135;
    
    ushort value = BitConverter.ToUInt16(new byte[2] { (byte)port1, (byte)port2 }, 0);
    ushort value2 = (ushort)(port1 + (port2 << 8)); //same output
    

提交回复
热议问题