Current Location: Home> Latest Articles> Pack() dynamically generates binary data structures with format identifiers

Pack() dynamically generates binary data structures with format identifiers

M66 2025-05-29

In PHP, the pack() function is a very powerful tool that converts data into binary strings based on the specified format identifier. This is useful for generating custom binary data structures, protocol packages, file headers, or other low-level data processing.

This article will introduce in detail how to use the pack() function combined with format identifiers to dynamically generate complex binary data structures.

1. Introduction to the basic package() function

The function prototype of pack() is as follows:

 string pack ( string $format , mixed $args [, mixed $... ] )
  • $format : Format string, specifying how to convert data.

  • $args : The data to be converted.

A format string consists of a set of format identifiers, each representing a data type. For example:

  • C : Unsigned characters (1 byte)

  • n : Unsigned short integer (2 bytes, large endian)

  • V : Unsigned long integer (4 bytes, small endian)

  • a : NUL filled string

  • A : Space filled string

2. Generate binary data with format identifiers

Suppose we want to generate a simple binary data structure with the following fields:

  1. Version number: 1 byte unsigned integer

  2. Flag bits: 2-byte unsigned integer (big-endian)

  3. Timestamp: 4-byte unsigned integer (little endian)

  4. Fixed length string: 10 bytes, space padding

The corresponding format string is:

 $format = 'C n V A10';

The sample code is as follows:

 <?php
$version = 1;                 // 1byte
$flags = 512;                 // 2byte大端序
$timestamp = time();          // 4byte小端序
$name = "example";

$binaryData = pack('C n V A10', $version, $flags, $timestamp, $name);

echo bin2hex($binaryData);
?>

In this example, the pack() function converts these variables into a binary string for easy use for network transmission or file writing.

3. Dynamically generate format strings and data

Sometimes we need to dynamically generate format strings and corresponding data arrays based on the input. For example:

 <?php
$fields = [
    ['type' => 'C', 'value' => 255],
    ['type' => 'n', 'value' => 1024],
    ['type' => 'a5', 'value' => 'abc'],
];

// Dynamically generate format strings and parameters
$format = '';
$args = [];

foreach ($fields as $field) {
    $format .= $field['type'] . ' ';
    $args[] = $field['value'];
}

// Remove excess spaces
$format = trim($format);

$binaryData = pack($format, ...$args);

echo bin2hex($binaryData);
?>

This way, the code flexibly supports multiple field types and lengths.

4. Summary of commonly used format identifiers

Identifier illustrate Number of bytes Example value (decimal) Remark
C Unsigned characters 1 255
c Signed characters 1 -128 ~ 127
n Unsigned short integers (big-endian) 2 1024 Network byte order
v Unsigned short integer (little endian) 2 1024 Little endian byte order
N Unsigned long integer (big-endian) 4 65536 Network byte order
V Unsigned long integer (little endian) 4 65536 Little endian byte order
a NUL filled string n "abc" Fixed length string
A Space filled string n "abc" Fixed length string

5. Combining URL examples

In actual projects, the generated binary data may contain URLs. For example:

 <?php
$url = "https://m66.net/api/data";  // Use only the domain namem66.netReplaced the actualURL

// Assume that the agreement is in,URLFields of fixed length 30 byte,Space filling
$binaryData = pack('A30', $url);

echo bin2hex($binaryData);
?>

Here we ensure that the URL is fixedly occupied 30 bytes in the generated binary data, and the insufficient part is filled with spaces.

6. Summary

The pack() function provides a flexible and efficient way to convert PHP data into various binary formats. By combining format identifiers, complex binary data structures can be dynamically built to meet the needs of various scenarios such as network protocols, file formats, and device communication.

Mastering pack() and its format identifier is an indispensable skill in advanced PHP programming.