Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain to me the pack() function in PHP?

I would like to know more about the pack() function in PHP: https://secure.php.net/manual/en/function.pack.php

I know it packs data into binary, but I'm not sure what all those v V n N c C mean and I was wondering if someone could be so kind as to give me a practical demonstration when to use which formats?

The online documentation, for a change, lacks of information, in my opinion.

like image 446
Tower Avatar asked Jun 12 '09 17:06

Tower


People also ask

What is PHP pack?

The pack() function is an inbuilt function in PHP which is used to pack the given parameter into a binary string in a given format. Syntax: pack( $format, $arguments )

What is the use of pack function?

The pack() function packs data into a binary string.


1 Answers

Those represent how you want the data you are packing to be represented in binary format:

so

$bin = pack("v", 1); => 0000000000000001 (16bit)

where

$bin = pack("V", 1) => 00000000000000000000000000000001 (32 bit)

It tells pack how you want the data represented in the binary data. The code below will demonstrate this. Note that you can unpack with a different format from what you packed the data as.

<?php  $bin = pack("S", 65535); $ray = unpack("S", $bin); echo "UNSIGNED SHORT VAL = ", $ray[1], "\n";  $bin = pack("S", 65536); $ray = unpack("S", $bin); echo "OVERFLOW USHORT VAL = ", $ray[1], "\n";  $bin = pack("V", 65536); $ray = unpack("V", $bin); echo "SAME AS ABOVE BUT WITH ULONG VAL = ", $ray[1], "\n"; ?> 
like image 153
RC. Avatar answered Oct 21 '22 08:10

RC.