This code is hereby placed in the public domain.
Please send comments, suggestions, and bug reports to lhf@tecgraf.puc-rio.br.
This is a simple Lua library for packing and unpacking binary data.
The library adds two functions to the string
library: pack
and unpack
.
Prototype:
ret = pack( F, x1, x2, ... )
Description:
Packs binary data into a string.
Parameters:
F
A string describing how the values
x1, x2, ...
are to be interpreted and formatted. Each letter in the format stringF
consumes one of the given values. The letter codes understood by pack are listed below (they are inspired by Perl's codes but are not the same). Numbers following letter codes inF
indicate repetitions.
x1, x2, ...
Values to pack into binary. Only values of type number or string are accepted.
Returns:
ret
A (binary) string containing the values packed as described in
F
.
Prototype:
val, next = unpack( s, F [,init] )
Description:
Packs binary data into a string.
Parameters:
s
A (binary) string containing data packed as if by pack.
F
A format string describing what is to be read from
s
init
An optional init marks where in
s
to begin reading the values.
Returns:
next
The first value returned by unpack is the next unread position in
s
, which can be used as the init position in a subsequent call tounpack
. This allows you tounpack
values in a loop or in several steps. If the position returned byunpack
is beyond the end ofs
, thens
has been exhausted; any calls tounpack
starting beyond the end ofs
will always returnnil
values.
val
One value per letter in
F
untilF
ors
is exhausted (the letters codes are the same as for pack, except that numbers followingA
are interpreted as the number of characters to read into the string, not as repetitions).
z
: zero-terminated string
p
: string preceded by length byte
P
: string preceded by length word
a
: string preceded by length size_t
A
: string
f
: float
d
: double
n
: Lua number
c
: char
b
: byte (unsigned char)
h
: short
H
: unsigned short
i
: int
I
: unsigned int
l
: long
L
: unsigned long
<
: little endian
>
: big endian
=
: native endian