有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java代码段字节数组到端口号

我有一个字节数组,其中包含6个字节,最后2个表示端口号,同时搜索将最后2个字节转换为端口号的方法,我遇到了这个代码段



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

这是可行的,但我需要澄清一下它是如何工作的


共 (3) 个答案

  1. # 1 楼答案

        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. # 2 楼答案

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

    通常,在网络数据包中,端口号以大端号传输(意味着地址越低的字节越重要)

    代码采用字节号i+4并将其用作MSB,字节i+5用作端口号的LSB

  3. # 3 楼答案

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

    基本上,它需要字节#5,向左移位8位,得到0101010100000000,然后使用按位or运算符将字节6替换为零