3

I'm writing a client for a binary socket protocol in PHP, and it's a pain. I'm currently using pack to convert numbers into binary strings, but it's lacking. Two options pack has are:

  • Write a signed 32 bit integer in machine byte order
  • Write an insigned 32 bit integer in big endian byte order

But I need to write signed 32 bit integers in big endian order, as with Java's DataOutputStream.writeInteger. pack doesn't have that option.

Is there a way to do this with pack, or to transform the output of pack, or maybe a better library for working with binary data in PHP?

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
  • 1
    Not sure if this helps, but here goes: http://www.phpclasses.org/package/2454-PHP-Serialize-and-unserialize-binary-data.html – Russell Dias Oct 05 '10 at 12:21

2 Answers2

2

Do you use the Zend Framework? If so, you can use the function Zend_Io_Writer::writeInt32BE()

Writes signed 32-bit integer as big-endian ordered binary data to the stream.

Or else you should take a look at the ZF-source how these guys handle this.

Bas van Dorst
  • 6,632
  • 3
  • 17
  • 12
0

The specification for PHP's pack() says that the unsigned/signed distinction only matters for unpack(), not pack().

So just use the 32 bit network byte order option (N).

caf
  • 233,326
  • 40
  • 323
  • 462
  • + 4 billion, doesn't that result in the same number? I also suspect this isn't very portable, see http://stackoverflow.com/questions/300840/force-php-integer-overflow – Bart van Heukelom Oct 05 '10 at 13:17
  • @Bart vna Heukelom: On further reflection, and checking the documentation, you can just use the unsigned option. – caf Oct 05 '10 at 13:49