dongwei7048 2012-05-02 18:24 采纳率: 100%
浏览 114
已采纳

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

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.

Specifically, in Java I use:

dataOutputStream.writeInt(number);

Then in PHP I read the file using:

$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)". I thought that int in java was always signed?

Is it possible to reliably read data encoded in Java in this way or not? 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. Otherwise of course I could use XML or JSON or something.

  • 写回答

2条回答 默认 最新

  • douliao8402 2012-05-02 18:36
    关注

    This is fine, as long as you don't need that extra bit. l (instead of N) would work on a big endian machine.

    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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入