我正在尝试将两个字节转换为无符号短字节,以便检索实际的服务器端口值。我将它基于回复格式下的这个协议规范。我尝试为此使用BitConverter.ToUint16(),但问题是,它似乎没有抛出预期值。请参阅下面的示例实现:
int bytesRead = 0;
while (bytesRead < ms.Length)
{
int first = ms.ReadByte() & 0xFF;
int second = ms.ReadByte() & 0xFF;
int third = ms.ReadByte() & 0xFF;
int fourth = ms.ReadByte() & 0xFF;
int port1 = ms.ReadByte();
int port2 = ms.ReadByte();
int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port1 , (byte)port2 }, 0);
string ip = String.Format("{0}.{1}.{2}.{3}:{4}-{5} = {6}", first, second, third, fourth, port1, port2, actualPort);
Debug.WriteLine(ip);
bytesRead += 6;
}
给定一个示例数据,假设对于两个字节值,我有 105 和 135,转换后的预期端口值应该是 27015,但我使用 BitConverter 得到的值是 34665。
我做错了吗?