Skip to content

23: Set Byte Order with pack() and unpack()

Write a signed integer and a float in network byte order. Endianness tells the reader which end of a sequence of bytes holds the most significant part.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable binary-endianness.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/23-binary-endianness/binary-endianness.php
binary-endianness.php
<?php
declare(strict_types=1);
$packet = pack('s>f>', -2, 1.5);
echo bin2hex($packet), PHP_EOL;
$decoded = unpack('s>status/f>scale', $packet);
printf("status=%d scale=%.1f\n", $decoded['status'], $decoded['scale']);
fffe3fc00000
status=-2 scale=1.5

The > modifier selects big-endian and < selects little-endian. PHP 8.6 recognizes the modifier immediately after a supported format code. For a legacy element name starting with one of those characters, put the repetition count before the name, as in s1<code.

  • An 8-bit code such as C has no byte order. Remove the modifier from those codes.

Switch both formats to little-endian and run the round trip again. Confirm the bytes change to feff0000c03f and the decoded values stay the same.

Continue with Locate a JSON Syntax Error.