【问题标题】:Snippet Clarification byte array to port number片段澄清字节数组到端口号
【发布时间】:2009-06-20 11:37:10
【问题描述】:

我有一个包含 6 个字节的字节数组,最后 2 个表示端口号,同时寻找一种方法,两个将这些最后一个字节转换为我遇到的这个 sn-p 的端口号,



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

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

【问题讨论】:

    标签: java arrays byte


    【解决方案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】:
        =======================
        |  byte 5  |  byte 6  |
        |----------|----------|
        | 01010101 | 01010101 |
        =======================
      

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

      【讨论】:

      • 如果原始字节的最高位为 1,则需要 & 0xFF 以防止结果 int 为负。
      • @John:谢谢。没有注意到 Java 标记。
      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 2015-08-17
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多