The struct
module shown in Example 4-6 contains functions to convert between binary strings and
Python tuples. The pack
function takes a format
string and one or more arguments, and returns a binary string. The
unpack
function takes a string and returns a
tuple.
Example 4-6. Using the struct Module
File: struct-example-1.py import struct # native byteorder buffer = struct.pack("ihb", 1, 2, 3) print repr(buffer) print struct.unpack("ihb", buffer) # data from a sequence, network byteorder data = [1, 2, 3] buffer = apply(struct.pack, ("!ihb",) + tuple(data)) print repr(buffer) print struct.unpack("!ihb", buffer) # in 2.0, the apply statement can also be written as: # buffer = struct.pack("!ihb", *data)' 01 00 00 00 02 00 03'
(1, 2, 3)
' 00 00 00 01 00 02 03'
(1, 2, 3)
3.137.217.198