pack and unpack

pack and unpack

pack:
====

pack
- It pack data into binary string.

Syntax:
=====

string pack ( string format [, mixed args])

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

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

a NUL-padded string

A SPACE-padded string

h Hex string, low nibble first

H Hex string, high nibble first

c signed 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

unpack:
=====

unpack — Unpack data from binary string

Syntax:
======

array unpack ( string format, string data)

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

Example:
=======
pack

$data = pack (”nc”,40,45);

The resulting binary string $data = (-

unpack

$arr = unpack (”nint/cchars”, $data);
The resulting Array $arr is
Array
(
[int] => 40
[chars] => 45
)

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.