简体   繁体   English

从PHP中的Java DataOutputStream读取二进制数据时的整数格式是什么?

[英]What integer format when reading binary data from Java DataOutputStream in PHP?

I'm aware that this is probably not the best idea but I've been playing around trying to read a file in PHP that was encoded using Java's DataOutputStream. 我知道这可能不是最好的主意,但我一直在尝试读取使用Java的DataOutputStream编码的PHP文件。

Specifically, in Java I use: 具体来说,在Java中我使用:

dataOutputStream.writeInt(number);

Then in PHP I read the file using: 然后在PHP中我使用以下方法读取文件:

$data = fread($handle, 4);
$number = unpack('N', $data);

The strange thing is that the only format character in PHP that gives the correct value is 'N', which is supposed to represent "unsigned long (always 32 bit, big endian byte order)". 奇怪的是PHP中唯一给出正确值的格式字符是'N',它应该表示“无符号长(总是32位,大端字节顺序)”。 I thought that int in java was always signed? 我以为java中的int总是签名?

Is it possible to reliably read data encoded in Java in this way or not? 是否可以以这种方式可靠地读取用Java编码的数据? In this case the integer will only ever need to be positive. 在这种情况下,整数只需要是正数。 It may also need to be quite large so writeShort() is not possible. 它可能还需要非常大,因此writeShort()是不可能的。 Otherwise of course I could use XML or JSON or something. 当然,我可以使用XML或JSON等。

This is fine, as long as you don't need that extra bit. 这很好,只要你不需要额外的位。 l (instead of N ) would work on a big endian machine. l (而不是N )可以在大型端机上运行。

Note, however, that the maximum number that you can store is 2,147,483,647 unless you want to do some math on the Java side to get the proper negative integer to represent the desired unsigned integer. 但请注意,您可以存储的最大数量是2,147,483,647,除非您想在Java端进行一些数学计算以获得正确的负整数来表示所需的无符号整数。

Note that a signed Java integer uses the two's complement method to represent a negative number, so it's not as easy as flipping a bit. 请注意,带符号的Java整数使用二进制补码方法来表示负数,因此它不像翻转那么容易。

DataOutputStream.writeInt : DataOutputStream.writeInt

Writes an int to the underlying output stream as four bytes, high byte first. 将int作为四个字节写入基础输出流,首先是高字节。

The formats available for the unpack function for signed integers all use machine dependent byte order. 可用于有符号整数的解包函数的格式都使用机器相关的字节顺序。 My guess is that your machine uses a different byte order than Java. 我的猜测是你的机器使用的字节顺序与Java不同。 If that is true, the DataOutputStream + unpack combination will not work for any signed primitive. 如果是这样,则DataOutputStream + unpack组合将不适用于任何已签名的基元。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM