我需要帮助将这行PHP翻译成Java pack( 'N', $data )。
$data应为7-9个数字字符,最后一个为空
我猜在通过该函数之后,它会被打包到一个很长的文件中。
它将通过套接字推送到服务器中,该服务器将运行以下代码:
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“打包”它?
EDIT:它通过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发布于 2012-07-12 04:59:33
经过一天的数学研究,我终于找到了答案。现在我已经弄清楚了,这实际上很简单。
在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这些数字是三位数,因此您需要将其转换为十六进制。仅供碰巧遇到这个问题的人参考。
发布于 2014-01-14 01:06:38
另一种选择是以类似于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();
}https://stackoverflow.com/questions/11357360
复制相似问题