blob: 1834cfd1af27a85f2f5703de8c7a663a0ffb0d1a [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
Mark Dickinson83f4cdf2010-06-15 08:45:06 +000023 of the corresponding C struct. To handle platform-independent data formats
24 or omit implicit pad bytes, use `standard` size and alignment instead of
25 `native` size and alignment: see :ref:`struct-alignment` for details.
Mark Dickinson093b25d2010-05-22 18:58:39 +000026
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
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000041 Return a bytes object containing the values *v1*, *v2*, ... packed according
42 to the format string *fmt*. The arguments must match the values required by
43 the format exactly.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45
46.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
47
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000048 Pack the values *v1*, *v2*, ... according to the format string *fmt* and
49 write the packed bytes into the writable buffer *buffer* starting at
50 position *offset*. Note that *offset* is a required argument.
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandl116aa622007-08-15 14:28:22 +000052
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000053.. function:: unpack(fmt, buffer)
Georg Brandl116aa622007-08-15 14:28:22 +000054
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000055 Unpack from the buffer *buffer* (presumably packed by ``pack(fmt, ...)``)
56 according to the format string *fmt*. The result is a tuple even if it
57 contains exactly one item. The buffer must contain exactly the amount of
58 data required by the format (``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
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000063 Unpack from *buffer* starting at position *offset*, according to the format
64 string *fmt*. The result is a tuple even if it contains exactly one
65 item. *buffer* must contain at least the amount of data required by the
66 format (``len(buffer[offset:])`` must be at least ``calcsize(fmt)``).
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068
69.. function:: calcsize(fmt)
70
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000071 Return the size of the struct (and hence of the bytes object produced by
72 ``pack(fmt, ...)``) corresponding to the format string *fmt*.
Georg Brandl116aa622007-08-15 14:28:22 +000073
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
Mark Dickinsonf9e091a2010-06-12 19:18:51 +000080packing and unpacking data. They are built up from :ref:`format-characters`,
81which specify the type of data being packed/unpacked. In addition, there are
82special characters for controlling the :ref:`struct-alignment`.
83
84
85.. _struct-alignment:
86
87Byte Order, Size, and Alignment
88^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
89
90By default, C types are represented in the machine's native format and byte
91order, and properly aligned by skipping pad bytes if necessary (according to the
92rules used by the C compiler).
93
94Alternatively, the first character of the format string can be used to indicate
95the byte order, size and alignment of the packed data, according to the
96following table:
97
Mark Dickinson83f4cdf2010-06-15 08:45:06 +000098+-----------+------------------------+----------+-----------+
99| Character | Byte order | Size | Alignment |
100+===========+========================+==========+===========+
101| ``@`` | native | native | native |
102+-----------+------------------------+----------+-----------+
103| ``=`` | native | standard | none |
104+-----------+------------------------+----------+-----------+
105| ``<`` | little-endian | standard | none |
106+-----------+------------------------+----------+-----------+
107| ``>`` | big-endian | standard | none |
108+-----------+------------------------+----------+-----------+
109| ``!`` | network (= big-endian) | standard | none |
110+-----------+------------------------+----------+-----------+
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000111
112If the first character is not one of these, ``'@'`` is assumed.
113
114Native byte order is big-endian or little-endian, depending on the host
115system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
116Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
117switchable endianness (bi-endian). Use ``sys.byteorder`` to check the
118endianness of your system.
119
120Native size and alignment are determined using the C compiler's
121``sizeof`` expression. This is always combined with native byte order.
122
Mark Dickinson83f4cdf2010-06-15 08:45:06 +0000123Standard size depends only on the format character; see the table in
124the :ref:`format-characters` section.
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000125
126Note the difference between ``'@'`` and ``'='``: both use native byte order, but
127the size and alignment of the latter is standardized.
128
129The form ``'!'`` is available for those poor souls who claim they can't remember
130whether network byte order is big-endian or little-endian.
131
132There is no way to indicate non-native byte order (force byte-swapping); use the
133appropriate choice of ``'<'`` or ``'>'``.
134
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000135Notes:
136
137(1) Padding is only automatically added between successive structure members.
138 No padding is added at the beginning or the end of the encoded struct.
139
140(2) No padding is added when using non-native size and alignment, e.g.
141 with '<', '>', '=', and '!'.
142
143(3) To align the end of a structure to the alignment requirement of a
144 particular type, end the format with the code for that type with a repeat
145 count of zero. See :ref:`struct-examples`.
146
147
148.. _format-characters:
Mark Dickinson093b25d2010-05-22 18:58:39 +0000149
150Format Characters
151^^^^^^^^^^^^^^^^^
152
Georg Brandl116aa622007-08-15 14:28:22 +0000153Format characters have the following meaning; the conversion between C and
Mark Dickinson881c1b42010-06-29 20:11:18 +0000154Python values should be obvious given their types. The 'Standard size' column
155refers to the size of the packed value in bytes when using standard size; that
156is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or
157``'='``. When using native size, the size of the packed value is
158platform-dependent.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000160+--------+-------------------------+--------------------+----------------+------------+
161| Format | C Type | Python type | Standard size | Notes |
162+========+=========================+====================+================+============+
163| ``x`` | pad byte | no value | | |
164+--------+-------------------------+--------------------+----------------+------------+
165| ``c`` | :ctype:`char` | bytes of length 1 | 1 | |
166+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000167| ``b`` | :ctype:`signed char` | integer | 1 | \(1) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000168+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000169| ``B`` | :ctype:`unsigned char` | integer | 1 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000170+--------+-------------------------+--------------------+----------------+------------+
171| ``?`` | :ctype:`_Bool` | bool | 1 | \(2) |
172+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000173| ``h`` | :ctype:`short` | integer | 2 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000174+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000175| ``H`` | :ctype:`unsigned short` | integer | 2 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000176+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000177| ``i`` | :ctype:`int` | integer | 4 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000178+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000179| ``I`` | :ctype:`unsigned int` | integer | 4 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000180+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000181| ``l`` | :ctype:`long` | integer | 4 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000182+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000183| ``L`` | :ctype:`unsigned long` | integer | 4 | |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000184+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000185| ``q`` | :ctype:`long long` | integer | 8 | \(3) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000186+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000187| ``Q`` | :ctype:`unsigned long | integer | 8 | \(3) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000188| | long` | | | |
189+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000190| ``f`` | :ctype:`float` | float | 4 | \(4) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000191+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000192| ``d`` | :ctype:`double` | float | 8 | \(4) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000193+--------+-------------------------+--------------------+----------------+------------+
194| ``s`` | :ctype:`char[]` | bytes | | \(1) |
195+--------+-------------------------+--------------------+----------------+------------+
196| ``p`` | :ctype:`char[]` | bytes | | \(1) |
197+--------+-------------------------+--------------------+----------------+------------+
Mark Dickinson0dafd712010-06-15 08:49:30 +0000198| ``P`` | :ctype:`void \*` | integer | | \(5) |
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000199+--------+-------------------------+--------------------+----------------+------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201Notes:
202
203(1)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000204 The ``c``, ``s`` and ``p`` conversion codes operate on :class:`bytes`
205 objects, but packing with such codes also supports :class:`str` objects,
206 which are encoded using UTF-8.
207
208(2)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000209 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl116aa622007-08-15 14:28:22 +0000210 C99. If this type is not available, it is simulated using a :ctype:`char`. In
211 standard mode, it is always represented by one byte.
212
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000213(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000214 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
215 the platform C compiler supports C :ctype:`long long`, or, on Windows,
216 :ctype:`__int64`. They are always available in standard modes.
217
Mark Dickinson83f4cdf2010-06-15 08:45:06 +0000218(4)
Mark Dickinson83f4cdf2010-06-15 08:45:06 +0000219 For the ``'f'`` and ``'d'`` conversion codes, the packed representation uses
220 the IEEE 754 binary32 (for ``'f'``) or binary64 (for ``'d'``) format,
221 regardless of the floating-point format used by the platform.
222
Mark Dickinson0dafd712010-06-15 08:49:30 +0000223(5)
Mark Dickinson83f4cdf2010-06-15 08:45:06 +0000224 The ``'P'`` format character is only available for the native byte ordering
225 (selected as the default or with the ``'@'`` byte order character). The byte
226 order character ``'='`` chooses to use little- or big-endian ordering based
227 on the host system. The struct module does not interpret this as native
228 ordering, so the ``'P'`` format is not available.
229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231A format character may be preceded by an integral repeat count. For example,
232the format string ``'4h'`` means exactly the same as ``'hhhh'``.
233
234Whitespace characters between formats are ignored; a count and its format must
235not contain whitespace though.
236
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000237For the ``'s'`` format character, the count is interpreted as the length of the
238bytes, not a repeat count like for the other format characters; for example,
Georg Brandl116aa622007-08-15 14:28:22 +0000239``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
240For packing, the string is truncated or padded with null bytes as appropriate to
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000241make it fit. For unpacking, the resulting bytes object always has exactly the
Georg Brandl116aa622007-08-15 14:28:22 +0000242specified number of bytes. As a special case, ``'0s'`` means a single, empty
243string (while ``'0c'`` means 0 characters).
244
Mark Dickinsonb40b9472009-03-29 16:58:21 +0000245When packing a value ``x`` using one of the integer formats (``'b'``,
246``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``,
247``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format
248then :exc:`struct.error` is raised.
249
250.. versionchanged:: 3.1
251 In 3.0, some of the integer formats wrapped out-of-range values and
252 raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254The ``'p'`` format character encodes a "Pascal string", meaning a short
Georg Brandl914a2182010-10-06 08:13:26 +0000255variable-length string stored in a *fixed number of bytes*, given by the count.
256The first byte stored is the length of the string, or 255, whichever is
257smaller. The bytes of the string follow. If the string passed in to
258:func:`pack` is too long (longer than the count minus 1), only the leading
259``count-1`` bytes of the string are stored. If the string is shorter than
260``count-1``, it is padded with null bytes so that exactly count bytes in all
261are used. Note that for :func:`unpack`, the ``'p'`` format character consumes
262``count`` bytes, but that the string returned can never contain more than 255
263bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000265For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl116aa622007-08-15 14:28:22 +0000266:const:`False`. When packing, the truth value of the argument object is used.
267Either 0 or 1 in the native or standard bool representation will be packed, and
268any non-zero value will be True when unpacking.
269
Mark Dickinson093b25d2010-05-22 18:58:39 +0000270
Mark Dickinson093b25d2010-05-22 18:58:39 +0000271
272.. _struct-examples:
273
274Examples
275^^^^^^^^
276
277.. note::
278 All examples assume a native byte order, size, and alignment with a
279 big-endian machine.
280
281A basic example of packing/unpacking three integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 >>> from struct import *
284 >>> pack('hhl', 1, 2, 3)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000285 b'\x00\x01\x00\x02\x00\x00\x00\x03'
286 >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
Georg Brandl116aa622007-08-15 14:28:22 +0000287 (1, 2, 3)
288 >>> calcsize('hhl')
289 8
290
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000291Unpacked fields can be named by assigning them to variables or by wrapping
292the result in a named tuple::
293
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000294 >>> record = b'raymond \x32\x12\x08\x01\x08'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000295 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
296
297 >>> from collections import namedtuple
298 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000299 >>> Student._make(unpack('<10sHHb', record))
300 Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Mark Dickinson093b25d2010-05-22 18:58:39 +0000302The ordering of format characters may have an impact on size since the padding
303needed to satisfy alignment requirements is different::
304
305 >>> pack('ci', '*', 0x12131415)
306 b'*\x00\x00\x00\x12\x13\x14\x15'
307 >>> pack('ic', 0x12131415, '*')
308 b'\x12\x13\x14\x15*'
309 >>> calcsize('ci')
310 8
311 >>> calcsize('ic')
312 5
313
314The following format ``'llh0l'`` specifies two pad bytes at the end, assuming
315longs are aligned on 4-byte boundaries::
316
317 >>> pack('llh0l', 1, 2, 3)
318 b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
319
320This only works when native size and alignment are in effect; standard size and
321alignment does not enforce any alignment.
322
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324.. seealso::
325
326 Module :mod:`array`
327 Packed binary storage of homogeneous data.
328
329 Module :mod:`xdrlib`
330 Packing and unpacking of XDR data.
331
332
333.. _struct-objects:
334
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000335Classes
Mark Dickinson093b25d2010-05-22 18:58:39 +0000336-------
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338The :mod:`struct` module also defines the following type:
339
340
341.. class:: Struct(format)
342
Mark Dickinson093b25d2010-05-22 18:58:39 +0000343 Return a new Struct object which writes and reads binary data according to
344 the format string *format*. Creating a Struct object once and calling its
345 methods is more efficient than calling the :mod:`struct` functions with the
346 same format since the format string only needs to be compiled once.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Benjamin Petersone41251e2008-04-25 01:59:09 +0000349 Compiled Struct objects support the following methods and attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Benjamin Petersone41251e2008-04-25 01:59:09 +0000351 .. method:: pack(v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Benjamin Petersone41251e2008-04-25 01:59:09 +0000353 Identical to the :func:`pack` function, using the compiled format.
354 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356
Benjamin Petersone41251e2008-04-25 01:59:09 +0000357 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Benjamin Petersone41251e2008-04-25 01:59:09 +0000359 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000362 .. method:: unpack(buffer)
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersone41251e2008-04-25 01:59:09 +0000364 Identical to the :func:`unpack` function, using the compiled format.
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000365 (``len(buffer)`` must equal :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367
Georg Brandlb044b2a2009-09-16 16:05:59 +0000368 .. method:: unpack_from(buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 Identical to the :func:`unpack_from` function, using the compiled format.
371 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373
Benjamin Petersone41251e2008-04-25 01:59:09 +0000374 .. attribute:: format
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Benjamin Petersone41251e2008-04-25 01:59:09 +0000376 The format string used to construct this Struct object.
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Benjamin Petersone41251e2008-04-25 01:59:09 +0000378 .. attribute:: size
Guido van Rossum04110fb2007-08-24 16:32:05 +0000379
Mark Dickinsonf9e091a2010-06-12 19:18:51 +0000380 The calculated size of the struct (and hence of the bytes object produced
381 by the :meth:`pack` method) corresponding to :attr:`format`.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000382