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.
pack
(PHP 4, PHP 5)
pack — Compacte des données dans une chaîne binaire
Description
Compacte les arguments args dans une chaîne binaire, suivant le format format .
L'idée vient du Perl et tout le formatage fonctionne de la même façon qu'en Perl, mais quelques formats manquent encore (comme "u")..
Notez 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.
De plus, notez que PHP enregistre de manière interne et intégrale les valeurs : cette représentation dépend de la machine. Si vous essayez d'enregistrer une valeur trop grande, elle risque d'être convertie en float et de donner lieu à des effets de bords vicieux.
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 bits dépendant de la machine) S entier court non signé (toujours 16 bits, ordre des bits dépendant de la machine) n entier cours non signé (toujours 16 bits, ordre des bits big endian) v entier cours non signé (toujours 16 bits, ordre des bits little endian) i entier signé (taille et ordre des bits dépendants de la machine) I entier non signé (taille et ordre des bits dépendants de la machine) l entier long signé (toujours 32 bits, ordre des bits dépendant de la machine) L entier long non signé (toujours 32 bits, ordre des bits dépendant de la machine) N entier long non signé (toujours 32 bits, ordre des bits big endian) V entier long non signé (toujours 32 bits, ordre des bits little endian) f nombre à virgule flottante (taille et représentation dépendantes de la machine) d nombre à virgule flottante double (taille et représentation dépendantes de la machine) x caractère NUL X Recule d'un caractère @ Remplit avec des NUL jusqu'à la position absolue - args
-
Valeurs de retour
Retourne une chaîne de caractères binaire contenant les données.
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.
pack
08-May-2008 04:26
25-Jan-2008 03:45
<?PHP
function ntohs($port) {
$b=pack("N", $port);
return substr($b,2,2);
}
?>
I've spent a number of hours (n>=2) finding how to do this,
it works like the c function 'ntohs', used for eg the socks5 proxy protocol.
06-Sep-2007 01:00
This is how I used pack to convert base2 to base64 since base_convert doesn't support base64
The base conversions don't work for long strings, which is why I convert 1 byte at a time
Hope this helps someone
function base2to64($base2) {
if ($remainbits = strlen($base2)%8) $base2 .= str_repeat('0',8-$remainbits);
$base64 = NULL;
for ($i=0;$i<strlen($base2);$i+=8) $base16 .= sprintf('%02x',bindec(sprintf('%08d',substr($base2,$i,8))));
return base64_encode(pack('H*',$base16));
}
function base64to2($base64) {
list($base16) = unpack('H*0',base64_decode($base64));
$base2 = NULL;
for ($i=0;$i<strlen($base16);$i++) $base2 .= sprintf('%04d',base_convert(substr($base16,$i,1),16,2));
return $base2;
}
16-Feb-2007 01:21
This is how you can produce a code that is in fact a picture.
(This code is a complete tool, copy it to a file, call it 'somehow.php' and produce your pictures as hexcode).
<!--// ***Begin of File*** //-->
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<input type="file" name="thefile"><input type="submit">
</form>
<?php
$rh = fopen ($_FILES['thefile']['tmp_name'], "r");
$pb = fread($rh, 8192);
fclose($rh);
$pc = bin2hex($pb);
$pd = wordwrap($pc, 76, "\".<br /> \n \"", 1);
echo "<TT>\$hexpic=\""."$pd"."\"\n</TT>;";
?>
<!--// ***End of File*** //-->
Copy the result in your site code somewhere. For to show the code as a picture you can use something like what dirk (at) camindo de wrote ...
<?php
$hexpic=".......................
.....................";
$data = pack("H" . strlen($hexpic), $hexpic);
header("Content-Type: image/png");
// maybe your is jpeg / gif / png
header("Last-Modified: " . date("r", filectime($_SERVER['SCRIPT_FILENAME'])));
header("Content-Length: " . strlen($data));
echo $data;
?>
have fun!
19-Jan-2007 12:22
Work around newsletter tracking:
include a transparent gif (1x1 pixel) with url = track.php and parameters.
track.php has to write the parameters e.g. into a database and provides the gif - using following code:
header("Content-Type: image/gif");
header("Content-Length: 49");
echo pack('H*',
'47494638396101000100910000000000ffffffff'
.'ffff00000021f90405140002002c000000000100'
.'01000002025401003b'
);
23-Mar-2006 01: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
13-Mar-2006 05: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];
}
11-Oct-2005 07:42
You will get the same effect with
<?php
function _readInt($fp)
{
return unpack('V', fread($fp, 4));
}
?>
or unpack('N', ...) for big-endianness.
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.
02-Sep-2004 08: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;
}
02-Oct-2003 08: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
10-Jul-2001 06: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 =)
10-Aug-2000 01: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!
