PHP pack() Function
Example
Pack data into a binary string:
Run Example »
Definition and Usage
The pack() function packs data into a binary string.
This is very useful in network transmission, file handling and data storage, especially when precise control over data format and byte order is required.
Syntax
string pack(string $format, mixed $arg1 [, mixed $arg2, ...])
$format: A string that specifies how the givenarg1,arg2, ... arguments are packed. Each character represents a data type and size.$arg1,$arg2, ...: The data to be packed. It can be an integer, a float, a string, etc.
The pack() function returns the packed binary string, or false if an error occurs.
| Parameters | Description |
|---|---|
| format | Required. Specifies the format used when packing data.
Possible values: Integers: |
c: Signed char (1 byte).C: Unsigned char (1 byte).s: Signed short (2 bytes, host byte order).S: Unsigned short (2 bytes, host byte order).l: Signed long (4 bytes, host byte order).L: Unsigned long (4 bytes, host byte order).q: Signed long long (8 bytes, host byte order).Q: Unsigned long long (8 bytes, host byte order).Float (floating point number):
f: Single-precision float (4 bytes, host byte order).d: Double-precision float (8 bytes, host byte order).
Strings and other types:
x: NUL byte (padding byte, no argument).a: NUL-terminated string (takes the argument as a string).A: Space-padded string (takes the argument as a string).@: NUL bytes padded to the specified length.
Technical Details
| Return Value: | Returns a binary string containing the data. |
|---|---|
| PHP Version: | 4+ |
| Changelog: | In PHP 5.5 the "Z" code was added, with the same function as "a" for Perl compatibility. |
More examples
Below are some examples of using the pack() function.
Pack an unsigned short and a string:
Example
$data
=
pack
(
'S'
,
65535
)
;
// Pack the unsigned short 65535
echo
bin2hex
(
$data
)
;
// Output: ffff
Pack a signed long and a string:
Example
$data
=
pack
(
'l'
,
2147483648
)
;
// Pack the signed long -2147483648
echo
bin2hex
(
$data
)
;
// Output: 0000000080000000
Pack a float and a string:
Example
$data
=
pack
(
'f'
,
3.14
)
;
// Pack the float 3.14
echo
bin2hex
(
$data
)
;
// Output: 4048f5c3
Notes
pack()The pack() function is a powerful tool for converting data into binary format, but you need to make sure you understand the meaning and usage of every character in the required format.- Byte order (endianness) issues: integers and floats may be represented differently on different systems; you can use the
pack()andunpack()function to ensure data is transmitted and parsed correctly across different systems. - You can use the
bin2hex()The bin2hex() function converts binary data into a hexadecimal string for output and debugging.
PHP Misc Reference Manual