pack

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

pack — Compacte des donnĂ©es dans une chaĂźne binaire

Description

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

Compacte les arguments args dans une chaĂźne binaire, suivant le format format.

Le concept vient du Perl et tout le formatage fonctionne de la mĂȘme façon qu'en Perl, mais quelques formats manquent encore (comme "u").

Il est Ă  noter que la distinction entre signĂ© et non signĂ© n'affecte que la fonction unpack(), tandis que la fonction pack() fournira le mĂȘme rĂ©sultat pour les deux formats.

Liste de paramĂštres

format

La chaĂźne de caractĂšres format consiste en des codes de format suivis par un argument rĂ©pĂ©teur optionnel. Le rĂ©pĂ©teur peut ĂȘtre soit une valeur entiĂšre, soit * pour une rĂ©pĂ©tition jusqu'Ă  la fin des donnĂ©es d'entrĂ©es. Pour a, A, h, H, le rĂ©pĂ©teur spĂ©cifie combien de caractĂšres d'une donnĂ©e est pris, pour @, c'est la position absolue oĂč l'on insĂšre les prochaines donnĂ©es, pour tout le reste, le rĂ©pĂ©teur spĂ©cifie combien d'arguments de donnĂ©es sont consommĂ©s et compactĂ©s dans la chaĂźne binaire rĂ©sultante.

Les formats actuellement acceptés sont :

CaractĂšres de formatage pour pack()
Code Description
a NUL - Une chaßne complétée avec null
A SPACE - Une chaßne complétée avec un espace
h Chaßne hexadécimale h, bit de poids faible en premier
H Chaßne hexadécimale H, bit de poids fort en premier
c CaractÚre signé
C CaractÚre non signé
s entier court signé (toujours sur 16 bits, ordre des octets dépendant de la machine)
S entier court non signé (toujours 16 bits, ordre des octets dépendant de la machine)
n entier court non signé (toujours 16 bits, ordre des octets big endian)
v entier court non signé (toujours 16 bits, ordre des octets little endian)
i entier signé (taille et ordre des octets dépendants de la machine)
I entier non signé (taille et ordre des octets dépendants de la machine)
l entier long signé (toujours 32 bits, ordre des octets dépendant de la machine)
L entier long non signé (toujours 32 bits, ordre des octets dépendant de la machine)
N entier long non signé (toujours 32 bits, ordre des octets big endian)
V entier long non signé (toujours 32 bits, ordre des octets little endian)
q entier doublement long signé (toujours 64 bits, ordre des octets dépendant de la machine)
Q entier doublement long non signé (toujours 64 bits, ordre des octets dépendant de la machine)
J entier doublement long non signé (toujours 64 bits, ordre des octets big endian)
P entier doublement long non signé (toujours 64 bits, ordre des octets little endian)
f nombre à virgule flottante (taille et représentation dépendantes de la machine)
g nombre à virgule flottante (taille dépendante de la machine, ordre des octets little endian)
G nombre à virgule flottante (taille dépendante de la machine, ordre des octets big endian)
d nombre à virgule flottante double (taille et représentation dépendantes de la machine)
e nombre à virgule flottante double (taille dépendante de la machine, ordre des octets little endian)
E nombre à virgule flottante double (taille dépendante de la machine, ordre des octets big endian)
x caractĂšre NUL
X Recule d'un caractĂšre
Z La chaßne terminée par NUL (ASCIIZ) sera complétée par la valeur NULL
@ Remplit avec des NUL jusqu'Ă  la position absolue
values

Valeurs de retour

Retourne une chaßne de caractÚres binaire contenant les données.

Historique

Version Description
8.0.0 Cette fonction ne retourne plus false en cas d'échec.
7.2.0 Les types float et double prennent en charge Big Endian et Little Endian.
7.0.15, 7.1.1 Les codes "e", "E", "g" et "G" ont été ajoutés pour activer la prise en charge de l'ordre des octets pour les nombres à virgule flottante simple et double précision.

Exemples

Exemple #1 Exemple avec pack()

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

La chaßne binaire résultante aura 6 octets de long, et contiendra la séquence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Notes

Attention

Les codes de format q, Q, J et P ne sont pas disponibles sur les versions de PHP 32 bits.

Attention

Il est à noter que PHP stocke en interne les valeurs int comme valeurs signées dépendantes de la machine. Les opérations sur les entiers qui mÚnent à des chiffres en dehors de l'espace de définition de l'int seront stockées dans des float. Lors de l'empaquetage de ses flottants en entiers, ils sont transtypés vers le type entier. Ceci peut éventuellement mener à une représentation inattendue des octets.

Le cas le plus classique est l'empaquetage de nombres non signĂ©s qui seraient reprĂ©sentables dans le type int si celui-ci Ă©tait non signĂ©. Sur les systĂšmes ayant un int d'une taille de 32-bits, le transtypage rĂ©sulte en un octet identique que si le type int Ă©tait non signĂ© (mĂȘme si cela reste dĂ©pendant de l'implĂ©mentation non signĂ© vers signĂ©, du standard C). Sur les systĂšmes ayant un int d'une taille de 64-bits, le float n'a souvent pas une mantisse assez large pour contenir la valeur sans perte de prĂ©cision. Si ces systĂšmes possĂšdent aussi un type C natif int 64-bits (la plupart des *NIX ne l'ont pas), le seul moyen d'utiliser le format de paquetage I dans les hautes valeurs est de crĂ©er des valeurs int nĂ©gatives avec la mĂȘme reprĂ©sentation des octets que la valeur non signĂ©e voulue correspondante.

Voir aussi

  • unpack() - DĂ©conditionne des donnĂ©es depuis une chaĂźne binaire
add a note

User Contributed Notes 10 notes

up
90
chadm at codeangel dot org ¶
14 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 ¶
10 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
18
plutus at gmx dot de ¶
25 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
13
FrozenFire ¶
15 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
6
j.s.hoekstra ¶
20 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
2
Patrik Fimml ¶
20 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
2
petepostma at gmail dot spam dot com ¶
13 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
2
php at nagler-ihlein dot de ¶
18 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
0
ru ¶
8 years ago
pack()
h    Hex string, low nibble first (not same hex2bin())
H    Hex string, high nibble first (same hex2bin())
up
-1
Ammar Hameed ¶
15 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);
?>