PHP 8.1.28 Released!

pack

(PHP 4, PHP 5, PHP 7, PHP 8)

packPackt Daten in eine binäre Zeichenkette

Beschreibung

pack(string $format, mixed ...$values): string

Packt die angegebenen Argumente unter Beachtung von format in eine binäre Zeichenkette.

Die Idee für diese Funktion entstammt Perl. Alle Formatierungs-Anweisungen funktionieren genau wie dort, allerdings fehlen in PHP einige Format-Codes von Perl (z. B. "u").

Beachten sie, dass der Unterschied zwischen vorzeichenlosen und vorzeichenbehafteten Werten nur Einfluss auf die Funktion unpack() hat, wogegen die Funktion pack() bei vorzeichenlosen und vorzeichenbehafteten Format-Codes dasselbe Ergebnis liefert.

Parameter-Liste

format

Die Zeichenkette format besteht aus Format-Codes, gefolgt von einem optionalen Wiederholungs-Argument. Dieses Argument kann ein ganzzahliger Wert sein oder ein * für Wiederholung bis ans Ende der Daten. Bei den Format-Codes a, A, h und H gibt das Wiederholungs-Argument an, wie viele gleiche Zeichen folgen. Im Zusammenhang mit "@" gibt das Wiederholungs-Argument die absolute Position an, ab der das nächste Zeichen steht. Bei allen anderen steht der Wiederholungs-Zähler für die Anzahl der benutzten Daten-Argumente, die in die sich ergebende binäre Zeichenkette gepackt werden sollen.

Zurzeit sind folgende Formate implementiert:

pack()-Formatzeichen
Code Beschreibung
a mit NUL gefüllte Zeichenkette
A mit Leerzeichen gefüllte Zeichenkette
h Hex-Zeichenkette, unterer Halbwert zuerst
H Hex-Zeichenkette, oberer Halbwert zuerst
c vorzeichenbehaftetes Zeichen
C vorzeichenloses Zeichen
s vorzeichenbehafteter Short-Typ (immer 16 Bit, Byte-Folge maschinenabhängig)
S vorzeichenloser Short-Typ (immer 16 Bit, Byte-Folge maschinenabhängig)
n vorzeichenloser Short-Typ (immer 16 Bit, Byte-Folge Big-Endian)
v vorzeichenloser Short-Typ (immer 16 Bit, Byte-Folge Little-Endian)
i vorzeichenbehaftete Ganzzahl (Größe und Byte-Folge maschinenabhängig)
I vorzeichenlose Ganzzahl (Größe und Byte-Folge maschinenabhängig)
l vorzeichenbehafteter Long-Typ (immer 32 Bit, Byte-Folge maschinenabhängig)
L vorzeichenloser Long-Typ (immer 32 Bit, Byte-Folge maschinenabhängig)
N vorzeichenloser Long-Typ (immer 32 Bit, Byte-Folge Big-Endian)
V vorzeichenloser Long-Typ (immer 32 Bit, Byte-Folge Little-Endian)
q vorzeichenbehafteter Long-Long-Typ (immer 64 Bit, maschinenabhängig)
Q vorzeichenloser Long-Long-Typ (immer 64 Bit, maschinenabhängig)
J vorzeichenloser Long-Long-Typ (immer 64 Bit, Byte-Folge Big-Endian)
P vorzeichenloser Long-Long-Typ (immer 64 Bit, Byte-Folge Little-Endian)
f Gleitkommazahl (maschinenabhängige Größe und Wiedergabe)
g Gleitkommazahl (maschinenabhängige Größe, Byte-Folge Little-Endian)
G Gleitkommazahl (maschinenabhängige Größe, Byte-Folge Big-Endian)
d Double-Typ (maschinenabhängige Größe und Wiedergabe)
e Double-Typ (maschinenabhängige Größe, Byte-Folge Little-Endian)
E Double-Typ (maschinenabhängige Größe, Byte-Folge Big-Endian)
x NUL Byte
X geht in der Zeichenkette ein Byte rückwärts
Z NUL-aufgefüllte Zeichenkette
@ NUL-Auffüllung bis zur absoluten Position

values

Rückgabewerte

Gibt die Daten als binäre Zeichenkette zurück.

Changelog

Version Beschreibung
8.0.0 Diese Funktion gibt bei einem Fehler nicht mehr false zurück.
7.2.0 float- und double-Typen unterstützen sowohl Big-Endian als auch Little-Endian.
7.0.15, 7.1.1 Die Codes "e", "E", "g" und "G" wurden hinzugefügt, um die Byte-Folgen-Unterstützung für float und double zu ermöglichen.

Beispiele

Beispiel #1 pack()-Beispiel

<?php
$binaerdaten
= pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

Die sich daraus ergebende binäre Zeichenkette ist sechs Bytes lang und enthält die Byte-Folge 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Anmerkungen

Achtung

Es ist zu beachten, dass PHP int-Werte intern als vorzeichenbehaftete Werte einer maschinenabhängigen Größe speichert (C-Typ long). Integer-Literale und Operationen, die Zahlen außerhalb der Grenzen des Typs int ergeben, werden als float gespeichert. Wenn diese Floats als Integer gepackt werden, werden sie zuerst in den Integer-Typ gewandelt. Dies kann u. U. ein nicht erwünschtes Byte-Muster ergeben.

Der wichtigste Fall ist das Packen vorzeichenloser Zahlen, die als int-Typ darstellbar wären, wenn dieser vorzeichenlos wäre. Auf Systemen wo der Typ int 32 Bit groß ist, resultiert die Umwandlung üblicherweise im selben Byte-Muster, wie wenn der int vorzeichenlos wäre (allerdings ist das auf implementierungsspezifische Konvertierungen von vorzeichenlosen in vorzeichenbehaftete Zahlen gemäß dem C-Standard angewiesen). Auf Systemen, wo der Typ int 64 Bit groß ist, hat float vermutlich keine Mantisse, die groß genug ist, um den Wert ohne Genauigkeitsverlust zu speichern. Haben diese Systeme ebenfalls einen nativen 64bit-C-int-Typ (die meisten UNIX-artigen Systeme haben das nicht), dann ist die einzige Möglichkeit, das Packformat I im oberen Bereich zu nutzen, negative int-Werte mit der gleichen Byte-Darstellung wie die gewünschten vorzeichenlosen Werte zu erzeugen.

Siehe auch

  • unpack() - Entpackt die Daten einer binäre Zeichenkette

add a note

User Contributed Notes 10 notes

up
84
chadm at codeangel dot org
12 years ago
If you'd like to understand pack/unpack. There is a tutorial here in perl, that works equally well in understanding it for php:

http://perldoc.perl.org/perlpacktut.html
up
35
stanislav dot eckert at vizson dot de
7 years ago
A helper class to convert integer to binary strings and vice versa. Useful for writing and reading integers to / from files or sockets.

<?php

class int_helper
{
public static function
int8($i) {
return
is_int($i) ? pack("c", $i) : unpack("c", $i)[1];
}

public static function
uInt8($i) {
return
is_int($i) ? pack("C", $i) : unpack("C", $i)[1];
}

public static function
int16($i) {
return
is_int($i) ? pack("s", $i) : unpack("s", $i)[1];
}

public static function
uInt16($i, $endianness=false) {
$f = is_int($i) ? "pack" : "unpack";

if (
$endianness === true) { // big-endian
$i = $f("n", $i);
}
else if (
$endianness === false) { // little-endian
$i = $f("v", $i);
}
else if (
$endianness === null) { // machine byte order
$i = $f("S", $i);
}

return
is_array($i) ? $i[1] : $i;
}

public static function
int32($i) {
return
is_int($i) ? pack("l", $i) : unpack("l", $i)[1];
}

public static function
uInt32($i, $endianness=false) {
$f = is_int($i) ? "pack" : "unpack";

if (
$endianness === true) { // big-endian
$i = $f("N", $i);
}
else if (
$endianness === false) { // little-endian
$i = $f("V", $i);
}
else if (
$endianness === null) { // machine byte order
$i = $f("L", $i);
}

return
is_array($i) ? $i[1] : $i;
}

public static function
int64($i) {
return
is_int($i) ? pack("q", $i) : unpack("q", $i)[1];
}

public static function
uInt64($i, $endianness=false) {
$f = is_int($i) ? "pack" : "unpack";

if (
$endianness === true) { // big-endian
$i = $f("J", $i);
}
else if (
$endianness === false) { // little-endian
$i = $f("P", $i);
}
else if (
$endianness === null) { // machine byte order
$i = $f("Q", $i);
}

return
is_array($i) ? $i[1] : $i;
}
}
?>

Usage example:
<?php
Header
("Content-Type: text/plain");
include(
"int_helper.php");

echo
int_helper::uInt8(0x6b) . PHP_EOL; // k
echo int_helper::uInt8(107) . PHP_EOL; // k
echo int_helper::uInt8("\x6b") . PHP_EOL . PHP_EOL; // 107

echo int_helper::uInt16(4101) . PHP_EOL; // \x05\x10
echo int_helper::uInt16("\x05\x10") . PHP_EOL; // 4101
echo int_helper::uInt16("\x05\x10", true) . PHP_EOL . PHP_EOL; // 1296

echo int_helper::uInt32(2147483647) . PHP_EOL; // \xff\xff\xff\x7f
echo int_helper::uInt32("\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL; // 2147483647

// Note: Test this with 64-bit build of PHP
echo int_helper::uInt64(9223372036854775807) . PHP_EOL; // \xff\xff\xff\xff\xff\xff\xff\x7f
echo int_helper::uInt64("\xff\xff\xff\xff\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL; // 9223372036854775807

?>
up
17
plutus at gmx dot de
23 years ago
Note that the the upper command in perl looks like this:

$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);
In PHP it seems that no whitespaces are allowed in the first parameter. So if you want to convert your pack command from perl -> PHP, don't forget to remove the whitespaces!
up
14
FrozenFire
13 years ago
If you need to unpack a signed short from big-endian or little-endian specifically, instead of machine-byte-order, you need only unpack it as the unsigned form, and then if the result is >= 2^15, subtract 2^16 from it.

And example would be:

<?php
$foo
= unpack("n", $signedbigendianshort);
$foo = $foo[1];
if(
$foo >= pow(2, 15)) $foo -= pow(2, 16);
?>
up
7
j.s.hoekstra
18 years ago
/* Convert float from HostOrder to Network Order */
function FToN( $val )
{
$a = unpack("I",pack( "f",$val ));
return pack("N",$a[1] );
}

/* Convert float from Network Order to HostOrder */
function NToF($val )
{
$a = unpack("N",$val);
$b = unpack("f",pack( "I",$a[1]));
return $b[1];
}
up
3
Patrik Fimml
18 years ago
You will get the same effect with

<?php
function _readInt($fp)
{
return
unpack('V', fread($fp, 4));
}
?>

or unpack('N', ...) for big-endianness.
up
3
php at nagler-ihlein dot de
15 years ago
Be aware of format code H always padding the 0 for byte-alignment to the right (for odd count of nibbles).

So pack("H", "7") results in 0x70 (ASCII character 'p') and not in 0x07 (BELL character)
as well as pack("H*", "347") results in 0x34 ('4') and 0x70 ('p') and not 0x03 and 0x47.
up
3
petepostma at gmail dot spam dot com
11 years ago
Even though in a 64-bit architecure intval(6123456789) = 6123456789, and sprintf('%b', 5000000000) = 100101010000001011111001000000000
pack will not treat anything passed to it as 64-bit. If you want to pack a 64-bit integer:

<?php
$big
= 5000000000;

$left = 0xffffffff00000000;
$right = 0x00000000ffffffff;

$l = ($big & $left) >>32;
$r = $big & $right;

$good = pack('NN', $l, $r);

$urlsafe = str_replace(array('+','/'), array('-','_'), base64_encode($good));

//done!

//rebuild:
$unurl = str_replace(array('-','_'), array('+','/'), $urlsafe);
$binary = base64_decode($unurl);

$set = unpack('N2', $tmp);
print_r($set);

$original = $set[1] << 32 | $set[2];
echo
$original, "\\r\\n";
?>

results in:
Array
(
[1] => 1
[2] => 705032704
)
5000000000

but ONLY on a 64-bit enabled machine and PHP distro.
up
1
Ammar Hameed
13 years ago
Using pack to write Arabic char(s) to a file.

<?php
$text
= "&#13574;&#13830;&#13830;";

$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");

$len = mb_strlen($text);

$bom = mb_convert_encoding("&#65534;", "unicode", "HTML-ENTITIES");

$fp = fopen('text.txt', 'w');

fwrite($fp, pack('a2', $bom));
fwrite($fp, pack("a{$len}", $text));
fwrite($fp, pack('a2', $bom));
fwrite($fp, pack('a2', "\n"));

fclose($fp);
?>
up
0
ru
6 years ago
pack()
h Hex string, low nibble first (not same hex2bin())
H Hex string, high nibble first (same hex2bin())
To Top