Converting 2 bytes to Short in C# Converting 2 bytes to Short in C# arrays arrays

Converting 2 bytes to Short in C#


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


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


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