blob: 7802fdb1a003126177cbd6784c556aba57c187da [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002:mod:`struct` --- Interpret bytes as packed binary data
Georg Brandl116aa622007-08-15 14:28:22 +00003=========================================================
4
5.. module:: struct
Benjamin Peterson4ae19462008-07-31 15:03:40 +00006 :synopsis: Interpret bytes as packed binary data.
Georg Brandl116aa622007-08-15 14:28:22 +00007
8.. index::
9 pair: C; structures
10 triple: packing; binary; data
11
12This module performs conversions between Python values and C structs represented
Benjamin Peterson4ae19462008-07-31 15:03:40 +000013as Python :class:`bytes` objects. It uses :dfn:`format strings` (explained
14below) as compact descriptions of the lay-out of the C structs and the
15intended conversion to/from Python values. This can be used in handling
16binary data stored in files or from network connections, among other sources.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18The module defines the following exception and functions:
19
20
21.. exception:: error
22
23 Exception raised on various occasions; argument is a string describing what is
24 wrong.
25
26
27.. function:: pack(fmt, v1, v2, ...)
28
Benjamin Peterson4ae19462008-07-31 15:03:40 +000029 Return a bytes containing the values ``v1, v2, ...`` packed according to the
Georg Brandl116aa622007-08-15 14:28:22 +000030 given format. The arguments must match the values required by the format
31 exactly.
32
33
34.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
35
36 Pack the values ``v1, v2, ...`` according to the given format, write the packed
37 bytes into the writable *buffer* starting at *offset*. Note that the offset is
38 a required argument.
39
Georg Brandl116aa622007-08-15 14:28:22 +000040
Benjamin Peterson4ae19462008-07-31 15:03:40 +000041.. function:: unpack(fmt, bytes)
Georg Brandl116aa622007-08-15 14:28:22 +000042
Benjamin Peterson4ae19462008-07-31 15:03:40 +000043 Unpack the bytes (presumably packed by ``pack(fmt, ...)``) according to the
Georg Brandl116aa622007-08-15 14:28:22 +000044 given format. The result is a tuple even if it contains exactly one item. The
Benjamin Peterson4ae19462008-07-31 15:03:40 +000045 bytes must contain exactly the amount of data required by the format
46 (``len(bytes)`` must equal ``calcsize(fmt)``).
Georg Brandl116aa622007-08-15 14:28:22 +000047
48
49.. function:: unpack_from(fmt, buffer[,offset=0])
50
51 Unpack the *buffer* according to tthe given format. The result is a tuple even
52 if it contains exactly one item. The *buffer* must contain at least the amount
53 of data required by the format (``len(buffer[offset:])`` must be at least
54 ``calcsize(fmt)``).
55
Georg Brandl116aa622007-08-15 14:28:22 +000056
57.. function:: calcsize(fmt)
58
Benjamin Peterson4ae19462008-07-31 15:03:40 +000059 Return the size of the struct (and hence of the bytes) corresponding to the
Georg Brandl116aa622007-08-15 14:28:22 +000060 given format.
61
62Format characters have the following meaning; the conversion between C and
63Python values should be obvious given their types:
64
65+--------+-------------------------+--------------------+-------+
66| Format | C Type | Python | Notes |
67+========+=========================+====================+=======+
68| ``x`` | pad byte | no value | |
69+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000070| ``c`` | :ctype:`char` | bytes of length 1 | |
Georg Brandl116aa622007-08-15 14:28:22 +000071+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000072| ``b`` | :ctype:`signed char` | integer | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +000073+--------+-------------------------+--------------------+-------+
74| ``B`` | :ctype:`unsigned char` | integer | |
75+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000076| ``?`` | :ctype:`_Bool` | bool | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +000077+--------+-------------------------+--------------------+-------+
78| ``h`` | :ctype:`short` | integer | |
79+--------+-------------------------+--------------------+-------+
80| ``H`` | :ctype:`unsigned short` | integer | |
81+--------+-------------------------+--------------------+-------+
82| ``i`` | :ctype:`int` | integer | |
83+--------+-------------------------+--------------------+-------+
Georg Brandlba956ae2007-11-29 17:24:34 +000084| ``I`` | :ctype:`unsigned int` | integer | |
Georg Brandl116aa622007-08-15 14:28:22 +000085+--------+-------------------------+--------------------+-------+
86| ``l`` | :ctype:`long` | integer | |
87+--------+-------------------------+--------------------+-------+
Georg Brandlba956ae2007-11-29 17:24:34 +000088| ``L`` | :ctype:`unsigned long` | integer | |
Georg Brandl116aa622007-08-15 14:28:22 +000089+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000090| ``q`` | :ctype:`long long` | integer | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +000091+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000092| ``Q`` | :ctype:`unsigned long | integer | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +000093| | long` | | |
94+--------+-------------------------+--------------------+-------+
95| ``f`` | :ctype:`float` | float | |
96+--------+-------------------------+--------------------+-------+
97| ``d`` | :ctype:`double` | float | |
98+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000099| ``s`` | :ctype:`char[]` | bytes | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +0000100+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000101| ``p`` | :ctype:`char[]` | bytes | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +0000102+--------+-------------------------+--------------------+-------+
103| ``P`` | :ctype:`void \*` | integer | |
104+--------+-------------------------+--------------------+-------+
105
106Notes:
107
108(1)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000109 The ``c``, ``s`` and ``p`` conversion codes operate on :class:`bytes`
110 objects, but packing with such codes also supports :class:`str` objects,
111 which are encoded using UTF-8.
112
113(2)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000114 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl116aa622007-08-15 14:28:22 +0000115 C99. If this type is not available, it is simulated using a :ctype:`char`. In
116 standard mode, it is always represented by one byte.
117
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000118(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000119 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
120 the platform C compiler supports C :ctype:`long long`, or, on Windows,
121 :ctype:`__int64`. They are always available in standard modes.
122
Georg Brandl116aa622007-08-15 14:28:22 +0000123A format character may be preceded by an integral repeat count. For example,
124the format string ``'4h'`` means exactly the same as ``'hhhh'``.
125
126Whitespace characters between formats are ignored; a count and its format must
127not contain whitespace though.
128
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000129For the ``'s'`` format character, the count is interpreted as the length of the
130bytes, not a repeat count like for the other format characters; for example,
Georg Brandl116aa622007-08-15 14:28:22 +0000131``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
132For packing, the string is truncated or padded with null bytes as appropriate to
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000133make it fit. For unpacking, the resulting bytes object always has exactly the
Georg Brandl116aa622007-08-15 14:28:22 +0000134specified number of bytes. As a special case, ``'0s'`` means a single, empty
135string (while ``'0c'`` means 0 characters).
136
137The ``'p'`` format character encodes a "Pascal string", meaning a short
138variable-length string stored in a fixed number of bytes. The count is the total
139number of bytes stored. The first byte stored is the length of the string, or
140255, whichever is smaller. The bytes of the string follow. If the string
141passed in to :func:`pack` is too long (longer than the count minus 1), only the
142leading count-1 bytes of the string are stored. If the string is shorter than
143count-1, it is padded with null bytes so that exactly count bytes in all are
144used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000145bytes, but that the string returned can never contain more than 255 bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Georg Brandl116aa622007-08-15 14:28:22 +0000147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000149For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl116aa622007-08-15 14:28:22 +0000150:const:`False`. When packing, the truth value of the argument object is used.
151Either 0 or 1 in the native or standard bool representation will be packed, and
152any non-zero value will be True when unpacking.
153
154By default, C numbers are represented in the machine's native format and byte
155order, and properly aligned by skipping pad bytes if necessary (according to the
156rules used by the C compiler).
157
158Alternatively, the first character of the format string can be used to indicate
159the byte order, size and alignment of the packed data, according to the
160following table:
161
162+-----------+------------------------+--------------------+
163| Character | Byte order | Size and alignment |
164+===========+========================+====================+
165| ``@`` | native | native |
166+-----------+------------------------+--------------------+
167| ``=`` | native | standard |
168+-----------+------------------------+--------------------+
169| ``<`` | little-endian | standard |
170+-----------+------------------------+--------------------+
171| ``>`` | big-endian | standard |
172+-----------+------------------------+--------------------+
173| ``!`` | network (= big-endian) | standard |
174+-----------+------------------------+--------------------+
175
176If the first character is not one of these, ``'@'`` is assumed.
177
178Native byte order is big-endian or little-endian, depending on the host system.
179For example, Motorola and Sun processors are big-endian; Intel and DEC
180processors are little-endian.
181
182Native size and alignment are determined using the C compiler's
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000183``sizeof`` expression. This is always combined with native byte order.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185Standard size and alignment are as follows: no alignment is required for any
186type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
187:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
188bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
189point numbers, respectively. :ctype:`_Bool` is 1 byte.
190
191Note the difference between ``'@'`` and ``'='``: both use native byte order, but
192the size and alignment of the latter is standardized.
193
194The form ``'!'`` is available for those poor souls who claim they can't remember
195whether network byte order is big-endian or little-endian.
196
197There is no way to indicate non-native byte order (force byte-swapping); use the
198appropriate choice of ``'<'`` or ``'>'``.
199
200The ``'P'`` format character is only available for the native byte ordering
201(selected as the default or with the ``'@'`` byte order character). The byte
202order character ``'='`` chooses to use little- or big-endian ordering based on
203the host system. The struct module does not interpret this as native ordering,
204so the ``'P'`` format is not available.
205
206Examples (all using native byte order, size and alignment, on a big-endian
207machine)::
208
209 >>> from struct import *
210 >>> pack('hhl', 1, 2, 3)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000211 b'\x00\x01\x00\x02\x00\x00\x00\x03'
212 >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
Georg Brandl116aa622007-08-15 14:28:22 +0000213 (1, 2, 3)
214 >>> calcsize('hhl')
215 8
216
217Hint: to align the end of a structure to the alignment requirement of a
218particular type, end the format with the code for that type with a repeat count
219of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the
220end, assuming longs are aligned on 4-byte boundaries. This only works when
221native size and alignment are in effect; standard size and alignment does not
222enforce any alignment.
223
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000224Unpacked fields can be named by assigning them to variables or by wrapping
225the result in a named tuple::
226
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000227 >>> record = b'raymond \x32\x12\x08\x01\x08'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000228 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
229
230 >>> from collections import namedtuple
231 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000232 >>> Student._make(unpack('<10sHHb', record))
233 Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235.. seealso::
236
237 Module :mod:`array`
238 Packed binary storage of homogeneous data.
239
240 Module :mod:`xdrlib`
241 Packing and unpacking of XDR data.
242
243
244.. _struct-objects:
245
246Struct Objects
247--------------
248
249The :mod:`struct` module also defines the following type:
250
251
252.. class:: Struct(format)
253
254 Return a new Struct object which writes and reads binary data according to the
255 format string *format*. Creating a Struct object once and calling its methods
256 is more efficient than calling the :mod:`struct` functions with the same format
257 since the format string only needs to be compiled once.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Benjamin Petersone41251e2008-04-25 01:59:09 +0000260 Compiled Struct objects support the following methods and attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Benjamin Petersone41251e2008-04-25 01:59:09 +0000262 .. method:: pack(v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Benjamin Petersone41251e2008-04-25 01:59:09 +0000264 Identical to the :func:`pack` function, using the compiled format.
265 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267
Benjamin Petersone41251e2008-04-25 01:59:09 +0000268 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Benjamin Petersone41251e2008-04-25 01:59:09 +0000270 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000273 .. method:: unpack(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Benjamin Petersone41251e2008-04-25 01:59:09 +0000275 Identical to the :func:`unpack` function, using the compiled format.
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000276 (``len(bytes)`` must equal :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278
Benjamin Petersone41251e2008-04-25 01:59:09 +0000279 .. method:: unpack_from(buffer[, offset=0])
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Benjamin Petersone41251e2008-04-25 01:59:09 +0000281 Identical to the :func:`unpack_from` function, using the compiled format.
282 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284
Benjamin Petersone41251e2008-04-25 01:59:09 +0000285 .. attribute:: format
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Benjamin Petersone41251e2008-04-25 01:59:09 +0000287 The format string used to construct this Struct object.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Benjamin Petersone41251e2008-04-25 01:59:09 +0000289 .. attribute:: size
Guido van Rossum04110fb2007-08-24 16:32:05 +0000290
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000291 The calculated size of the struct (and hence of the bytes) corresponding
Benjamin Petersone41251e2008-04-25 01:59:09 +0000292 to :attr:`format`.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000293