Module pack

A library for packing and unpacking binary data.

The library adds two functions to the string library: pack and unpack.

Supported letter codes:

  • '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
  • 'x': unsigned char
  • '<': little endian
  • '>': big endian
  • '=': native endian
  • '{': unbreakable little endian
  • '}': unbreakable big endian

This library was made by Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br) with contributions from Ignacio CastaƱo (castanyo@yahoo.es) and Roberto Ierusalimschy (roberto@inf.puc-rio.br). Original library can be found here.

Usage:

require"pack"
local bindata = string.pack("zf", "foo", 4.2)
local _, mystring, myfloat = string.unpack(bindata, "zf")
 

Type pack

pack.pack(F, x1)

Pack binary data into a string.

pack.unpack(s, F, init)

Unpacks a binary string into values.

Type pack

Field(s)

pack.pack(F, x1)

Pack binary data into a string.

The letter codes understood by pack are listed above in module description. Numbers following letter codes indicate repetitions.

Parameters

  • F : a string describing how the values x1, x2, ... are to be interpreted and formatted. Each letter in the format string F consumes one of the given values.

  • x1 : x2, ... : variable number of values. Only values of type number or string are accepted.

Return value

a (binary) string containing the values packed as described in F.

Usage:

require"pack"
local bindata = string.pack("zf", "foo", 4.2)

pack.unpack(s, F, init)

Unpacks a binary string into values.

The letters codes are the same as for pack, except that numbers following 'A' are interpreted as the number of characters to read into the string and not as repetitions. 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 to unpack. This allows you to unpack values in a loop or in several steps.

Parameters

  • s : is a (binary) string containing data packed as if by pack

  • F : is a format string describing what is to be read from s

  • init : optional init marks where in s to begin reading the values

Return values

  1. the next unread position in s, followed by one value per letter in F until F or s is exhausted.

  2. nil if either s has been exhausted or init is bigger than the length of the s

Usage:

 require"pack"
 local _,mystring,myfloat = string.unpack(bindata, "zf")