PHP pack()Functions
Definition and Usage
The pack() function packs data into a binary string.
This is very useful in network transmission, file processing, and data storage, especially when precise control over data format and byte order is needed.
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. Can be integers, floats, or strings, 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:
Floating point numbers:
Strings and other types:
|
| args+ | Optional. Specifies one or more arguments to be packed. |
Technical Details
| Return value: | Returns a binary string containing the data. |
|---|---|
| PHP version: | 4+ |
| Changelog: | The "Z" code was added in PHP 5.5 and has the same functionality as "a" used for Perl compatibility. |
More Examples
Below are some examples using the pack() function.
Pack an unsigned short integer and a string:
Example
$data = pack('S', 65535); // Pack unsigned short integer 65535
echo bin2hex($data); // Output: ffff
echo bin2hex($data); // Output: ffff
Pack a signed long integer and a string:
Example
$data = pack('l', -2147483648); // Pack signed long integer -2147483648
echo bin2hex($data); // Output: 0000000080000000
echo bin2hex($data); // Output: 0000000080000000
Pack a float and a string:
Example
$data = pack('f', 3.14); // Pack float 3.14
echo bin2hex($data); // Output: 4048f5c3
echo bin2hex($data); // Output: 4048f5c3
Notes
pack()The function is a powerful tool for converting data into a binary format, but you need to ensure that you understand the meaning and usage of each character in the required format.- Endianness (byte order) issue: On different systems, integers and floating-point numbers may be represented differently. You can use
pack()andunpack()the function to ensure correct transmission and parsing of data between different systems. - You can use
bin2hex()the function to convert binary data into a hexadecimal string for output and debugging.
PHP Misc Reference Manual Other Extensions