In PHP, the pack() function is used to package data into binary strings in the specified format. Many developers use it when dealing with network protocols or binary files. pack("N", 12345) is a typical usage, which means that the integer 12345 is packaged into a 4-byte binary string in large-endian byte order (network byte order).
But sometimes you may find that the results you get after using pack("N", 12345) are inconsistent with the output you expected, and even look "strange" when converted to hexadecimal or output. Why is this? This article helps you analyze the principles behind it.
The format character "N" is represented in pack() :
N : unsigned long (4 bytes, 32-bit unsigned integer)
Big-endian, that is, the high byte is in front and the low byte is in the back
For example, the hexadecimal representation of integer 12345 is 0x3039 , and its corresponding 4-byte big-endian is:
00 00 30 39
Therefore, the binary string generated by pack("N", 12345) should be converted into hexadecimal to these 4 bytes.
Many people observe that the results “look wrong”, and common reasons include:
Directly output binary strings to the browser or terminal , containing many invisible characters, or some bytes are parsed into control characters, which looks like garbled code.
The binary result is not converted to a readable format , such as hexadecimal or base64.
The expectation of the result does not match the actual meaning , for example, thinking that pack("N", 12345) will directly output the numeric string "12345".
Suppose we write the following PHP code:
<?php
$binary = pack("N", 12345);
echo bin2hex($binary);
?>
The result of the operation is:
00003039
This is the expected 4-byte big-endian result.
If you use echo $binary; directly, you will see garbled code or blank, because $binary is binary data, not ordinary text.
Error demonstration:
<?php
echo pack("N", 12345);
?>
When output to a web page or terminal, you will see garbled code or no visible characters. This makes you mistakenly think that the result of pack() is wrong.
pack("N", 12345) returns a 4-byte binary string in big-endian byte order, representing the number 12345.
The result is binary data, not the string "12345".
When viewing the results, it is best to convert it into a readable format using bin2hex() or similar methods.
Direct output of binary may result in seemingly "strange" results, but not errors.
<?php
// Put the number12345Packed into4Byte big-endian binary
$binary = pack("N", 12345);
// Shows a hexadecimal representation of binary,Convenient observation
echo "Hex representation: " . bin2hex($binary) . "\n";
// Can also be used unpack Anti-decompression
$unpacked = unpack("N", $binary);
echo "Unpacked number: " . $unpacked[1] . "\n";
?>
Output after execution:
Hex representation: 00003039
Unpacked number: 12345
PHP official documentation about pack
Understand the importance of Endian for binary data processing
The relationship between network protocol and binary data