blob: e924d39f9f47628e6bb57fddb3e9a6f8aa24d9b4 [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001:mod:`struct` --- Interpret bytes as packed binary data
Georg Brandlb044b2a2009-09-16 16:05:59 +00002=======================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: struct
Benjamin Peterson4ae19462008-07-31 15:03:40 +00005 :synopsis: Interpret bytes as packed binary data.
Georg Brandl116aa622007-08-15 14:28:22 +00006
7.. index::
8 pair: C; structures
9 triple: packing; binary; data
10
11This module performs conversions between Python values and C structs represented
Mark Dickinson093b25d2010-05-22 18:58:39 +000012as Python :class:`bytes` objects. This can be used in handling binary data
13stored in files or from network connections, among other sources. It uses
14:ref:`struct-format-strings` as compact descriptions of the layout of the C
15structs and the intended conversion to/from Python values.
16
17.. note::
18
19 By default, the result of packing a given C struct includes pad bytes in
20 order to maintain proper alignment for the C types involved; similarly,
21 alignment is taken into account when unpacking. This behavior is chosen so
22 that the bytes of a packed struct correspond exactly to the layout in memory
23 of the corresponding C struct. To omit pad bytes, use `standard` size and
24 alignment instead of `native` size and alignment: see :ref:`struct-alignment`
25 for details.
26
27Functions and Exceptions
28------------------------
Georg Brandl116aa622007-08-15 14:28:22 +000029
30The module defines the following exception and functions:
31
32
33.. exception:: error
34
Mark Dickinson093b25d2010-05-22 18:58:39 +000035 Exception raised on various occasions; argument is a string describing what
36 is wrong.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38
39.. function:: pack(fmt, v1, v2, ...)
40
Benjamin Peterson4ae19462008-07-31 15:03:40 +000041 Return a bytes containing the values ``v1, v2, ...`` packed according to the
Georg Brandl116aa622007-08-15 14:28:22 +000042 given format. The arguments must match the values required by the format
43 exactly.
44
45
46.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
47
Mark Dickinson093b25d2010-05-22 18:58:39 +000048 Pack the values ``v1, v2, ...`` according to the given format, write the
49 packed bytes into the writable *buffer* starting at *offset*. Note that the
50 offset is a required argument.
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandl116aa622007-08-15 14:28:22 +000052
Benjamin Peterson4ae19462008-07-31 15:03:40 +000053.. function:: unpack(fmt, bytes)
Georg Brandl116aa622007-08-15 14:28:22 +000054
Benjamin Peterson4ae19462008-07-31 15:03:40 +000055 Unpack the bytes (presumably packed by ``pack(fmt, ...)``) according to the
Mark Dickinson093b25d2010-05-22 18:58:39 +000056 given format. The result is a tuple even if it contains exactly one item.
57 The bytes must contain exactly the amount of data required by the format
Benjamin Peterson4ae19462008-07-31 15:03:40 +000058 (``len(bytes)`` must equal ``calcsize(fmt)``).
Georg Brandl116aa622007-08-15 14:28:22 +000059
60
Georg Brandlb044b2a2009-09-16 16:05:59 +000061.. function:: unpack_from(fmt, buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +000062
Benjamin Petersone0124bd2009-03-09 21:04:33 +000063 Unpack the *buffer* according to the given format. The result is a tuple even
Mark Dickinson093b25d2010-05-22 18:58:39 +000064 if it contains exactly one item. The *buffer* must contain at least the
65 amount of data required by the format (``len(buffer[offset:])`` must be at
66 least ``calcsize(fmt)``).
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068
69.. function:: calcsize(fmt)
70
Benjamin Peterson4ae19462008-07-31 15:03:40 +000071 Return the size of the struct (and hence of the bytes) corresponding to the
Georg Brandl116aa622007-08-15 14:28:22 +000072 given format.
73
Mark Dickinson093b25d2010-05-22 18:58:39 +000074.. _struct-format-strings:
75
76Format Strings
77--------------
78
79Format strings are the mechanism used to specify the expected layout when
80packing and unpacking data. They are built up from format characters, which
81specify the type of data being packed/unpacked. In addition, there are
82special characters for controlling the byte order, size, and alignment.
83
84Format Characters
85^^^^^^^^^^^^^^^^^
86
Georg Brandl116aa622007-08-15 14:28:22 +000087Format characters have the following meaning; the conversion between C and
88Python values should be obvious given their types:
89
Mark Dickinson093b25d2010-05-22 18:58:39 +000090+--------+-------------------------+--------------------+------------+
91| Format | C Type | Python | Notes |
92+========+=========================+====================+============+
93| ``x`` | pad byte | no value | |
94+--------+-------------------------+--------------------+------------+
95| ``c`` | :ctype:`char` | bytes of length 1 | |
96+--------+-------------------------+--------------------+------------+
97| ``b`` | :ctype:`signed char` | integer | \(1),\(4) |
98+--------+-------------------------+--------------------+------------+
99| ``B`` | :ctype:`unsigned char` | integer | \(4) |
100+--------+-------------------------+--------------------+------------+
101| ``?`` | :ctype:`_Bool` | bool | \(2) |
102+--------+-------------------------+--------------------+------------+
103| ``h`` | :ctype:`short` | integer | \(4) |
104+--------+-------------------------+--------------------+------------+
105| ``H`` | :ctype:`unsigned short` | integer | \(4) |
106+--------+-------------------------+--------------------+------------+
107| ``i`` | :ctype:`int` | integer | \(4) |
108+--------+-------------------------+--------------------+------------+
109| ``I`` | :ctype:`unsigned int` | integer | \(4) |
110+--------+-------------------------+--------------------+------------+
111| ``l`` | :ctype:`long` | integer | \(4) |
112+--------+-------------------------+--------------------+------------+
113| ``L`` | :ctype:`unsigned long` | integer | \(4) |
114+--------+-------------------------+--------------------+------------+
115| ``q`` | :ctype:`long long` | integer | \(3), \(4) |
116+--------+-------------------------+--------------------+------------+
117| ``Q`` | :ctype:`unsigned long | integer | \(3), \(4) |
118| | long` | | |
119+--------+-------------------------+--------------------+------------+
120| ``f`` | :ctype:`float` | float | |
121+--------+-------------------------+--------------------+------------+
122| ``d`` | :ctype:`double` | float | |
123+--------+-------------------------+--------------------+------------+
124| ``s`` | :ctype:`char[]` | bytes | \(1) |
125+--------+-------------------------+--------------------+------------+
126| ``p`` | :ctype:`char[]` | bytes | \(1) |
127+--------+-------------------------+--------------------+------------+
128| ``P`` | :ctype:`void \*` | integer | |
129+--------+-------------------------+--------------------+------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131Notes:
132
133(1)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000134 The ``c``, ``s`` and ``p`` conversion codes operate on :class:`bytes`
135 objects, but packing with such codes also supports :class:`str` objects,
136 which are encoded using UTF-8.
137
138(2)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000139 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl116aa622007-08-15 14:28:22 +0000140 C99. If this type is not available, it is simulated using a :ctype:`char`. In
141 standard mode, it is always represented by one byte.
142
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000143(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000144 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
145 the platform C compiler supports C :ctype:`long long`, or, on Windows,
146 :ctype:`__int64`. They are always available in standard modes.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148A format character may be preceded by an integral repeat count. For example,
149the format string ``'4h'`` means exactly the same as ``'hhhh'``.
150
151Whitespace characters between formats are ignored; a count and its format must
152not contain whitespace though.
153
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000154For the ``'s'`` format character, the count is interpreted as the length of the
155bytes, not a repeat count like for the other format characters; for example,
Georg Brandl116aa622007-08-15 14:28:22 +0000156``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
157For packing, the string is truncated or padded with null bytes as appropriate to
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000158make it fit. For unpacking, the resulting bytes object always has exactly the
Georg Brandl116aa622007-08-15 14:28:22 +0000159specified number of bytes. As a special case, ``'0s'`` means a single, empty
160string (while ``'0c'`` means 0 characters).
161
Mark Dickinsonb40b9472009-03-29 16:58:21 +0000162When packing a value ``x`` using one of the integer formats (``'b'``,
163``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``,
164``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format
165then :exc:`struct.error` is raised.
166
167.. versionchanged:: 3.1
168 In 3.0, some of the integer formats wrapped out-of-range values and
169 raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
170
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172The ``'p'`` format character encodes a "Pascal string", meaning a short
173variable-length string stored in a fixed number of bytes. The count is the total
174number of bytes stored. The first byte stored is the length of the string, or
175255, whichever is smaller. The bytes of the string follow. If the string
176passed in to :func:`pack` is too long (longer than the count minus 1), only the
177leading count-1 bytes of the string are stored. If the string is shorter than
178count-1, it is padded with null bytes so that exactly count bytes in all are
179used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000180bytes, but that the string returned can never contain more than 255 bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000184For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl116aa622007-08-15 14:28:22 +0000185:const:`False`. When packing, the truth value of the argument object is used.
186Either 0 or 1 in the native or standard bool representation will be packed, and
187any non-zero value will be True when unpacking.
188
Mark Dickinson093b25d2010-05-22 18:58:39 +0000189
190.. _struct-alignment:
191
192Byte Order, Size, and Alignment
193^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194
195By default, C types are represented in the machine's native format and byte
Georg Brandl116aa622007-08-15 14:28:22 +0000196order, and properly aligned by skipping pad bytes if necessary (according to the
197rules used by the C compiler).
198
199Alternatively, the first character of the format string can be used to indicate
200the byte order, size and alignment of the packed data, according to the
201following table:
202
203+-----------+------------------------+--------------------+
204| Character | Byte order | Size and alignment |
205+===========+========================+====================+
206| ``@`` | native | native |
207+-----------+------------------------+--------------------+
208| ``=`` | native | standard |
209+-----------+------------------------+--------------------+
210| ``<`` | little-endian | standard |
211+-----------+------------------------+--------------------+
212| ``>`` | big-endian | standard |
213+-----------+------------------------+--------------------+
214| ``!`` | network (= big-endian) | standard |
215+-----------+------------------------+--------------------+
216
217If the first character is not one of these, ``'@'`` is assumed.
218
219Native byte order is big-endian or little-endian, depending on the host system.
220For example, Motorola and Sun processors are big-endian; Intel and DEC
221processors are little-endian.
222
223Native size and alignment are determined using the C compiler's
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000224``sizeof`` expression. This is always combined with native byte order.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226Standard size and alignment are as follows: no alignment is required for any
227type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
228:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
229bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
230point numbers, respectively. :ctype:`_Bool` is 1 byte.
231
232Note the difference between ``'@'`` and ``'='``: both use native byte order, but
233the size and alignment of the latter is standardized.
234
235The form ``'!'`` is available for those poor souls who claim they can't remember
236whether network byte order is big-endian or little-endian.
237
238There is no way to indicate non-native byte order (force byte-swapping); use the
239appropriate choice of ``'<'`` or ``'>'``.
240
241The ``'P'`` format character is only available for the native byte ordering
242(selected as the default or with the ``'@'`` byte order character). The byte
243order character ``'='`` chooses to use little- or big-endian ordering based on
244the host system. The struct module does not interpret this as native ordering,
245so the ``'P'`` format is not available.
246
Mark Dickinson093b25d2010-05-22 18:58:39 +0000247Notes:
248
249(1) Padding is only automatically added between successive structure members.
250 No padding is added at the beginning or the end of the encoded struct.
251
252(2) No padding is added when using non-native size and alignment, e.g.
253 with '<', '>', '=', and '!'.
254
255(3) To align the end of a structure to the alignment requirement of a
256 particular type, end the format with the code for that type with a repeat
257 count of zero. See :ref:`struct-examples`.
258
259
260.. _struct-examples:
261
262Examples
263^^^^^^^^
264
265.. note::
266 All examples assume a native byte order, size, and alignment with a
267 big-endian machine.
268
269A basic example of packing/unpacking three integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271 >>> from struct import *
272 >>> pack('hhl', 1, 2, 3)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000273 b'\x00\x01\x00\x02\x00\x00\x00\x03'
274 >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
Georg Brandl116aa622007-08-15 14:28:22 +0000275 (1, 2, 3)
276 >>> calcsize('hhl')
277 8
278
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000279Unpacked fields can be named by assigning them to variables or by wrapping
280the result in a named tuple::
281
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000282 >>> record = b'raymond \x32\x12\x08\x01\x08'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000283 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
284
285 >>> from collections import namedtuple
286 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000287 >>> Student._make(unpack('<10sHHb', record))
288 Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Mark Dickinson093b25d2010-05-22 18:58:39 +0000290The ordering of format characters may have an impact on size since the padding
291needed to satisfy alignment requirements is different::
292
293 >>> pack('ci', '*', 0x12131415)
294 b'*\x00\x00\x00\x12\x13\x14\x15'
295 >>> pack('ic', 0x12131415, '*')
296 b'\x12\x13\x14\x15*'
297 >>> calcsize('ci')
298 8
299 >>> calcsize('ic')
300 5
301
302The following format ``'llh0l'`` specifies two pad bytes at the end, assuming
303longs are aligned on 4-byte boundaries::
304
305 >>> pack('llh0l', 1, 2, 3)
306 b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
307
308This only works when native size and alignment are in effect; standard size and
309alignment does not enforce any alignment.
310
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312.. seealso::
313
314 Module :mod:`array`
315 Packed binary storage of homogeneous data.
316
317 Module :mod:`xdrlib`
318 Packing and unpacking of XDR data.
319
320
321.. _struct-objects:
322
Mark Dickinson093b25d2010-05-22 18:58:39 +0000323Objects
324-------
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326The :mod:`struct` module also defines the following type:
327
328
329.. class:: Struct(format)
330
Mark Dickinson093b25d2010-05-22 18:58:39 +0000331 Return a new Struct object which writes and reads binary data according to
332 the format string *format*. Creating a Struct object once and calling its
333 methods is more efficient than calling the :mod:`struct` functions with the
334 same format since the format string only needs to be compiled once.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Benjamin Petersone41251e2008-04-25 01:59:09 +0000337 Compiled Struct objects support the following methods and attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Benjamin Petersone41251e2008-04-25 01:59:09 +0000339 .. method:: pack(v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Benjamin Petersone41251e2008-04-25 01:59:09 +0000341 Identical to the :func:`pack` function, using the compiled format.
342 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344
Benjamin Petersone41251e2008-04-25 01:59:09 +0000345 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Benjamin Petersone41251e2008-04-25 01:59:09 +0000347 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000350 .. method:: unpack(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Benjamin Petersone41251e2008-04-25 01:59:09 +0000352 Identical to the :func:`unpack` function, using the compiled format.
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000353 (``len(bytes)`` must equal :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355
Georg Brandlb044b2a2009-09-16 16:05:59 +0000356 .. method:: unpack_from(buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000357
Benjamin Petersone41251e2008-04-25 01:59:09 +0000358 Identical to the :func:`unpack_from` function, using the compiled format.
359 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
Benjamin Petersone41251e2008-04-25 01:59:09 +0000362 .. attribute:: format
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersone41251e2008-04-25 01:59:09 +0000364 The format string used to construct this Struct object.
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Benjamin Petersone41251e2008-04-25 01:59:09 +0000366 .. attribute:: size
Guido van Rossum04110fb2007-08-24 16:32:05 +0000367
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000368 The calculated size of the struct (and hence of the bytes) corresponding
Benjamin Petersone41251e2008-04-25 01:59:09 +0000369 to :attr:`format`.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000370