php[tek] 2018 : Call for Speakers

pack

(PHP 4, PHP 5)

packPack data into binary string

Description

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into binary string according to format.

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Parameters

format

The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

Currently implemented formats are:

pack() format characters
Code Description
a NUL-padded string
A SPACE-padded string
h Hex string, low nibble first
H Hex string, high nibble first
csigned char
C unsigned char
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)
n unsigned short (always 16 bit, big endian byte order)
v unsigned short (always 16 bit, little endian byte order)
i signed integer (machine dependent size and byte order)
I unsigned integer (machine dependent size and byte order)
l signed long (always 32 bit, machine byte order)
L unsigned long (always 32 bit, machine byte order)
N unsigned long (always 32 bit, big endian byte order)
V unsigned long (always 32 bit, little endian byte order)
f float (machine dependent size and representation)
d double (machine dependent size and representation)
x NUL byte
X Back up one byte
@ NUL-fill to absolute position

args

Return Values

Returns a binary string containing data.

Examples

Example #1 pack() example

<?php
$binarydata 
pack("nvc*"0x12340x56786566);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Notes

Caution

Note that PHP internally stores integer values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the integer type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the integer type if it were unsigned. In systems where the integer type has a 32-bit size, the cast usually results in the same byte pattern as if the integer were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the integer type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create integer negative values with the same byte representation as the desired unsigned value.

See Also

  • unpack() - Unpack data from binary string

add a note add a note

User Contributed Notes 20 notes

up
40
chadm at codeangel dot org
5 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
20
stanislav dot eckert at vizson dot de
1 year 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
13
FrozenFire
7 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
12
plutus at gmx dot de
17 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 -> intege clasd=100518&page=function.pack&vote=down" title="Vote down!" class="usernotes-vo3o clat" id="Hcom7653">
uInt 0n.pa comman;vote=down" title="Vote down!" class="u comm-voteu">up
up
12
plutus at gmx dot de17 commandago
plutus at gmx dot de179308mandago
Note that the th9308man; command in perl looks like this:

Clikr'sfoo decsee(),f pre> /p> &ppage=functioa0x34, 0x to / fexpress="/ma bytitsx to / -x34, 0xequivalthats or sockets.class
($i, 16$inpuoo ?>
$f !pan class="default">16is_notes">
, 16$inpuoo ($i<">// machine byte order
&nbsn>?>    spaPtract bytaxx34, 0pan clint_helper($i, $signed'H*'span class="keyword">);
?base_=functi>
($f = ""hp"$slen($$f $i = $ouo0.=s> $i = $d"> .=s$cnbsp;   &span>
Usad">(hp"
up
up
13
FrozenFirem
?ass="date" title="2000-08-10 04:14">1710932votego
If you'd like to932votm command in perl looks like this:

Even nversioinas ho spsigtf('%b', 5000000000) = 1n>101s1span>01s111110s1span>0000rameterdiv> willf prets="tbr y nanpbr lly, it 2^16ho UsaI00518&pagetead ofho =
unpackbig-an>("n"&nbsnlass="keyword">an class="default">16$left-an>("n"&nbsnlass="k>an class="default">16$rer C-an>("n"&nbsnlass="keyword">an class="default">16$l-an>(16$big-an>( w>an class="default">16$leftspan class="keyword">);
ss="default">16
xff\x7f"an class="default">16$rn>[1big-an>( w>an class="default">16$rer C machine byte order
&nbsnlass="keyword">an class="default">16$goodn>[1, $signed'NN'span class="keyword">);
?$/ machine byte order
&nbs>
?$4an class="keyword">, <)nlass="keyword">an class="default">16
$urlsaf4-an>("n"$s_replac4an class="keyword">];
i(an>$signed'+'span class="keyword">);
span class="default">$signed'/'span class="keyword">);
$signed'-'span class="keyword">);
span class="default">$signed'_'span class="keyword">);
$i
plutus at gmx dot de1757697oteago
, 16$goodspan class="keyword">);
an class="default">">?>an class="default">16$unurl-an>(>$s_replac4an class="keyword">];
i(an>$signed'-'span class="keyword">);
span class="default">$signed'_'span class="keyword">);
$signed'+'span class="keyword">);
span class="default">$signed'/'span class="keyword">);
an class="default">16
$urlsaf4an class="keyword">,
<)nlass="k1bio / fan>("n"
FrozenFirem.to.my.dev">//.quis.cxass="date" title="2000-08-10 04:14">1780621oteago
If you need to9852vot; command in perl looks like this:

Us nanpbckpagewritalArabic char(s) bytaxfile.span>class (>$signednv> #13574;v> #13830;v> #13830;     if (?$tf y-an>(efault">?mb_=functi_en lies">
, 16$tf yspan class="keyword">);
);
      &>) . );
er
$le/span>(mb_>$slen>
, 16$tf yspan class="keyword">);
$bom-an>(efault">?mb_=functi_en lies">
, >$signednv> #65534;     if () . );
      &>) . );
er
$fp-an>(efault">?fopen>
, >$signed'tf y.txt'span class="keyword">);
);
fwritapan class="keyword">) ? "pack"
, <>?n>, $signed'a2'span class="keyword">);
?$b>?asxff\xff\xff\xff\x7f"vphan>fwritapan class="keyword">) ? "pack"
, <>?n>, $signed"apan class="keyword">, {per$le/pan class="keyword">, }span class="default">$signed"span class="keyword">);
?$tf yspan class="keyword">);
>
) ? "pack"
, <>?n>, $signed'a2'span class="keyword">);
?$b>?asxff\xff\xff\xff\x7f"vphapan clper
fwritapan class="keyword">) ? "pack"
Note that the th90142">; command in perl looks like this:

Thes word">(st. ecpossibility bytgio3o cla<?php
v>
unpac>
, ::si2 toan class="keyword">, 10 machine byte order
&nbs>
?xff\x7f"1unpac>
, ::si2 toan class="keyword">, 10 machine byte order
&nbs>
?xff\x7f"1unpac>
, :: to2s/>    }
$signed"11111111111111111111111111110110"span class="keyword">);
?xff\x7f"10">unpac>
, :: to2s/>    }
$signed"00000000000000000000000000001s1s"span class="keyword">);
?xff\x7f"10">unpaceyword">an class="default">">?>st. unpac>
, ($i, $s/>    }
>?$bitn>) {
       xff\x7f"
unpac{ ameterlass="default"rd">=== (span><-
, 16);
/span>?$bitn>) {1f\x7f"(slan>2, 15)) ?$bitn>) {1f\x7f"=== (span><1">?>positio3oor zero ameterlass="default"lass="default"pan class="keyword">, { ameterlass="default"lass="default"lass="default"pan class="keyword">">1biofan>("n"
, 16$s/>    }
>10 machine byte order
&nbs>pan class="default">15
)) ">?>paly, i$bitna">1bio_le/gth-an>("n"$slen>
, 16$ toan class="keyword">, <)nlass="klass="default"lass="default"lass="default"rd">=== (ss="default">16$bitn>) {pow("n"$s_rep="tb>
, );
?$bitn>) {lbio_le/gth>) {16$ toan class="keyword">, ">?>negatio3 ameterlass="default"lass="default"pan class="keyword">, { ameterlass="default"lass="default"lass="default"pan class="keyword">">1s>(><-$s/>    }
-, 16);
/span>?$bitn>) {">1biofan>("n"
, 16$s/>    }
>10 machine byte order
&nbs>pan class="default">15
)) ">1bio_le/gth-an>("n"$slen>
, 16$ toan class="keyword">, <)nlass="klass="default"lass="default"lass="default"rd">=== (ss="default">16$bitn>) {pow("n"$s_rep="tb>
, );
?$bitn>) {lbio_le/gth>) {16$ toan class="keyword">, ($i<$ toan class="keyword">, unpaceyword">an class="default">">?>bio / f, ist. unpac>
, ($i    }
$i<$ toan class="keyword">, <>/span>?$bitn>) {
       xff\x7f"
unpac{ ameterlass="default"rd">=== , 16$ toan class="keyword">,
<)= />       $bitn>) {=== , 16$btoan class="keyword">, <>/span>?0 machine byte order
&nbs>pan class="default">15
1f\x7f"1">?>positio3oor zero ameterlass="default"lass="default"pan class="keyword">, { ameterlass="default"lass="default"lass="default"pan class="keyword">">1s>(>"n"
FrozenFire?ass="date" title="2000-08-10 04:14">177761voteago
plutus at gmx dot de1796214">ego
uat" cham((/pserializepd">(ec6)e o rrectrou nee`ig to / _/pserialize32`ain ig to / .c =t sho(httpopensource.dy">
53">
up
up
13
FrozenFire?ass="date" title="2000-08-10 04:14">17104151otego