有 Java 编程相关的问题?

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

PHP的Java包(“N”,$str)

我需要帮助将这行PHP翻译成Java pack( 'N', $data )

$data应为7-9个数字字符,最后一个为空

我猜在完成这个功能之后,它会被打包成一个很长的文件

它将通过一个socket被推入一个服务器,该服务器将运行以下操作:

byte[] abyte = datagrampacket.getData();
c(abyte, 7, datagrampacket.getLength())

和c(…)详情如下:

public static int c(byte[] abyte, int i, int j) {
    return 0 > j - i - 4 ? 0 : abyte[i] << 24 | (abyte[i + 1] & 255) << 16 | (abyte[i + 2] & 255) << 8 | abyte[i + 3] & 255;
}

我猜上面的函数只是将其扩展回原来的$data

有人知道我如何用java“打包”它吗

编辑:它通过php对数据做了什么:

Stripped Received Data:
array
  0 => string '13231786�' (length=9)
  1 => string '/31/33/32/33/31/37/38/36/0' (length=26) <--- dechex(ord()) for each char above
Packed Data:
array
  0 => string '�Éæª' (length=4)
  1 => string '/0/c9/e6/aa' (length=11) <--- dechex(ord()) for each char above

共 (2) 个答案

  1. # 1 楼答案

    经过一天的数学研究,我终于找到了答案。现在我明白了,其实很简单

    在java中:

    int x = (int) Math.floor(j/2^16);
    int y = (int) Math.floor((j-(x*65536))/2^8);
    int z = (int) Math.floor(j-((x*2^16)+(y*2^8)));
    
    x = 2nd character
    y = 3rd character
    z = 4th character
    

    这些数字是三位数,所以需要将其转换为十六进制。仅供偶然发现这个问题的人参考

  2. # 2 楼答案

    另一个选项是以类似于Java gist for PHP/Perl pack/unpack的方式使用ByteBuffer:

    static String packN(int value) {
        byte[] bytes = ByteBuffer.allocate(4).putInt(new Integer(value)).array();
        return new String(bytes, 'UTF-8');
    }
    
    static int unpackN(String value) {
        return ByteBuffer.wrap(value.bytes).getInt();
    }