PBE logo

Struct Module - Interpret strings as packed binary dataΒΆ

http://docs.python.org/library/struct.html

This module performs conversions between Python values and C structs represented as Python strings.

pack( fmt, v1, v2, ...) - Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

unpack( fmt, string) - Unpack the string (presumably packed by pack(fmt, ...)) according to the given format.

calcsize( fmt) - Return the size of the struct (and hence of the string) corresponding to the given format.

Examples from Python LibRef:

# h - short int, l - long, s - string, H - usigned short,
# b - signed char, see LibRef for the full list

pack('hhl', 1, 2, 3)   # '\x00\x01\x00\x02\x00\x00\x00\x03'
unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')   # (1, 2, 3)
calcsize('hhl')   # 8

record = 'raymond   \x32\x12\x08\x01\x08'
name, serialnum, school, gradelevel = unpack('<10sHHb', record)

from collections import namedtuple
Student = namedtuple('Student', 'name serialnum school gradelevel')
Student._make(unpack('<10sHHb', s))
# Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)