Converting 2 bytes to Short in C#

前端 未结 3 496
清歌不尽
清歌不尽 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条回答
  • To work on both little and big endian architectures, you must do something like:

    if (BitConverter.IsLittleEndian)
        actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);
    else
        actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port1 , (byte)port2 }, 0);
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题