I am trying to port the following Python code to PHP, but I can't find the PHP equivalent to Python's struct
. (and I specifically need an equivalent to struct.calcsize()
) Is there any PHP equivalent that I could use?
import struct
attr_fmt = ">iii4x"
attr_size = struct.calcsize(self.attr_fmt)
EDIT:
For those that are not familiar with Python, but are with PHP, from the struct
manual page:
This module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the int开发者_开发知识库ended conversion to/from Python values.
I'm not familiar with Python's struct, but it looks a bit like PHP's pack
and unpack
. I'm not aware of any direct way to determine the size before hand.
Here's an example that I believe is the same as yours:
$fmt = 'N3x4'; // three 32-bit big endian integers followed by 4 bytes of padding
$s = pack($fmt, 0, 0, 0); // pack the data into a string
$size = strlen($s); // find the length of the data
In this example, I chose three dummy 0
s to use as the arguments for the three integers.
To unpack the data, it would look like:
$fmt = 'N3/x4';
$a = unpack($fmt, $s);
echo $a[0];
精彩评论