我正在尝试将两个字节转换为无符号短整型,以便检索实际的服务器端口值。我基于协议规范下的回复格式进行操作。我尝试使用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。
我是否操作错误?