我有一个包含6个字节的字节数组,最后的2表示端口号,在搜索方法2将这些最后的字节转换为端口号时,
int port = 0;
port |= peerList[i+4] & 0xFF;
port <<= 8;
port |= peerList[i+5] & 0xFF;它可以工作,但我需要澄清一下它是如何工作的?
发布于 2009-06-20 11:42:54
======================= |字节5|字节6||-|-|| 01010101 | 01010101 | =======================
基本上,它接受字节#5,向左移位8位,产生0101010100000000,然后使用逐位或运算符将字节6放在零的位置。
发布于 2009-06-20 11:42:33
int port = 0; // Start with zero
port |= peerList[i+4] & 0xFF; // Assign first byte to port using bitwise or.
port <<= 8; // Shift the bits left by 8 (so the byte from before is on the correct position)
port |= peerList[i+5] & 0xFF; // Assign the second, LSB, byte to port.发布于 2009-06-20 11:41:04
代码简单地从数组中取出最后两个字节,并将它们用作一个大端数字。
通常,在网络数据包中,端口号是以大端字节序传输的(这意味着地址越低的字节越重要)。
代码取字节号i+4作为端口号的最低有效位,字节i+5作为端口号的最低有效位。
https://stackoverflow.com/questions/1021463
复制相似问题