我有一个包含6个字节的字节数组,最后2个代表端口号,同时搜索两个将这些最后转换为字节的方式转换为我已经遇到此代码片段的端口号,



            int port = 0;
        port |= peerList[i+4] & 0xFF;
        port <<= 8;
        port |= peerList[i+5] & 0xFF;

它有效,但我需要澄清它是如何工作的?

有帮助吗?

解决方案

  =======================
  |  byte 5  |  byte 6  |
  |----------|----------|
  | 01010101 | 01010101 |
  =======================

基本上,它需要字节#5,向左移位8位,得到 0101010100000000 ,然后使用按位或运算符将字节6放在零的位置。

其他提示

    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.

代码只从数组中获取最后2个字节,并将它们用作大端数字。

通常在网络数据包中,端口号以big-endian传输(意味着地址较低的字节更为重要)。

代码取字节编号i + 4并用作MSB,字节i + 5用作端口号的LSB。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top