pack

(PHP 3, PHP 4, PHP 5)

pack -- Pack data into binary string

Description

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

Pack given arguments into binary string according to format. Returns binary string containing data.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. 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 are

表格 1. pack() format characters

CodeDescription
aNUL-padded string
ASPACE-padded string
hHex string, low nibble first
HHex string, high nibble first
csigned char
Cunsigned char
ssigned short (always 16 bit, machine byte order)
Sunsigned short (always 16 bit, machine byte order)
nunsigned short (always 16 bit, big endian byte order)
vunsigned short (always 16 bit, little endian byte order)
isigned integer (machine dependent size and byte order)
Iunsigned integer (machine dependent size and byte order)
lsigned long (always 32 bit, machine byte order)
Lunsigned long (always 32 bit, machine byte order)
Nunsigned long (always 32 bit, big endian byte order)
Vunsigned long (always 32 bit, little endian byte order)
ffloat (machine dependent size and representation)
ddouble (machine dependent size and representation)
xNUL byte
XBack up one byte
@NUL-fill to absolute position

例子 1. pack() example

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

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

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.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

See also unpack().


add a note add a note User Contributed Notes
Newdawn.dk
23-Mar-2006 08:25
When trying to create a ZIP file using the pack function - I experienced trouble with the "a" code - It converted all chars correct from the std. ASCII charset but not more language specific like .
It seems that ZIP files do not use the same HEX for these as everything else does.
The fix was a quick workaround but you'll probably get the picture:
function UniHex($str) {
   //     
   //These are simply one HEX code being replaced by another to correct the issue
   $except = array("E6"=>"91","F8"=>"9B","E5"=>"86","C6"=>"92","D8"=>"9D",    "C5"=>"8F");
   for($i = 0; $i < strlen($str); $i++) {
       $hex = bin2hex(substr($str, $i, 1));
       if ($except[strtoupper($hex)])
           $hex = $except[strtoupper($hex)];
       $return .= $hex;
   }
   return $return;
}
And then i replaced an "a100" code with "H".strlen(uniHex($mystring))

This is like i said a quick workaround, but if you find the real reason for this i'd be happy to see it
j.s.hoekstra
14-Mar-2006 12:57
/* 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];
}
Patrik Fimml
12-Oct-2005 01:42
You will get the same effect with

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

or unpack('N', ...) for big-endianness.
20-Feb-2005 03:09
I needed to convert binary values from a file to integers.

Maybe there is something simpler, but the snippets i saw above seemed a little convoluted:

function bin2asc ($binary)
{
   $val = 0;

   for ($i = strlen($binary) - 1; $i >= 0; $i--) {
       $ch = substr($binary, $i, 1);
       $val = ($val << 8) | ord($ch);
   }

   return $val;
}

This was called like the following from a binary file:

function _readInt($fp)
{
   return bin2asc(fread($fp, 4));
}

Note that the for loop should be reversed for network byte order instead of intel byte order.  Also the conversion will work with any number of bytes, but will happily overflow.
zilinex at yahoo dot com
02-Sep-2004 02:12
a cool function to converrt numbers to Persian numbers(utf-8)
origin: http://www.farsiweb.info/jalali/jalali.phps

function farsinum($str)
{
  $ret = "";
  for ($i = 0; $i < strlen($str); ++$i) {
       $c = $str[$i];
       if( $c >= '0' && $c <= '9' )
               $out .= pack("C*", 0xDB, 0xB0 + $c);
       else
               $ret .= $c;
  }
  return $ret;
}
Jurgen Braam
03-Oct-2003 02:39
take note: if you produce binary files using PHP on multiple platforms, that you use one of the machine-independent pack options.

This means 's' 'S' 'i' 'I' 'd' and 'f' are _EVIL_ :) Took me some time to figure out what my Excel-generator what futzing about :) Turned out the production machine was a Sun Sparc. I develop on my own x86 Linux server.

Hope this helps anyone...
c-ya,
Jurgen
master at dreamphp dot com
02-Sep-2001 07:48
^-^ Simple version.

function bin2asc ($temp) {
  $len = strlen($temp);
  for ($i=0;$i<$len;$i+=8) $data.=chr(bindec(substr($temp,$i,8)));
  return $data;
}

function asc2bin ($temp) {
  $len = strlen($temp);
  for ($i=0; $i<$len; $i++) $data.=sprintf("%08b",ord(substr($temp,$i,1)));
  return $data;
}
mfisch[at]kaz[dot]com
11-Jul-2001 12:53
If you are trying to do ascii <--> binary conversions like me;
you probably found that unlike the perl pack functions, these wont help too much. Attached are two functions I wrote to accomplish this task.
<br>
function bin2asc ($binary)
{
  $i = 0;
  while ( strlen($binary) > 3 )
  {
   $byte[$i] = substr($binary, 0, 8);
   $byte[$i] = base_convert($byte[$i], 2, 10);
   $byte[$i] = chr($byte[$i]);
   $binary = substr($binary, 8);
   $ascii = "$ascii$byte[$i]";
  }
  return $ascii;
}
<br>
function asc2bin ($ascii)
{
  while ( strlen($ascii) > 0 )
  {
   $byte = ""; $i = 0;
   $byte = substr($ascii, 0, 1);
   while ( $byte != chr($i) ) { $i++; }
   $byte = base_convert($i, 10, 2);
   $byte = str_repeat("0", (8 - strlen($byte)) ) . $byte; # This is an endian (architexture) specific line, you may need to alter it.
   $ascii = substr($ascii, 1);
   $binary = "$binary$byte";
  }
  return $binary;
}
<br>
Im not sure these are the most efficient functions, but surely alot faster than loading up a perl interpreter for every binary conversion =)
plutus at gmx dot de
10-Aug-2000 07:14
Note that the the upper command in perl looks like this:<br>
$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);<br>
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!