blob: f1002a5ed7415a24c618b2abb0af61ec393d64ca [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001:mod:`struct` --- Interpret bytes as packed binary data
Georg Brandl7f01a132009-09-16 15:58:14 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Brandl7f01a132009-09-16 15:58:14 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Dickinson6abf1822010-04-12 21:00:59 +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 Dickinson6abf1822010-04-12 21:00:59 +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
Mark Dickinsonc5935772010-04-03 15:54:36 +0000148(4)
149 When attempting to pack a non-integer using any of the integer conversion
150 codes, if the non-integer has a :meth:`__index__` method then that method is
151 called to convert the argument to an integer before packing.
152
153 .. versionchanged:: 3.2
154 Use of the :meth:`__index__` method for non-integers is new in 3.2.
155
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157A format character may be preceded by an integral repeat count. For example,
158the format string ``'4h'`` means exactly the same as ``'hhhh'``.
159
160Whitespace characters between formats are ignored; a count and its format must
161not contain whitespace though.
162
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000163For the ``'s'`` format character, the count is interpreted as the length of the
164bytes, not a repeat count like for the other format characters; for example,
Georg Brandl116aa622007-08-15 14:28:22 +0000165``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
166For packing, the string is truncated or padded with null bytes as appropriate to
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000167make it fit. For unpacking, the resulting bytes object always has exactly the
Georg Brandl116aa622007-08-15 14:28:22 +0000168specified number of bytes. As a special case, ``'0s'`` means a single, empty
169string (while ``'0c'`` means 0 characters).
170
Mark Dickinsonb40b9472009-03-29 16:58:21 +0000171When packing a value ``x`` using one of the integer formats (``'b'``,
172``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``,
173``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format
174then :exc:`struct.error` is raised.
175
176.. versionchanged:: 3.1
177 In 3.0, some of the integer formats wrapped out-of-range values and
178 raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
179
180
Georg Brandl116aa622007-08-15 14:28:22 +0000181The ``'p'`` format character encodes a "Pascal string", meaning a short
182variable-length string stored in a fixed number of bytes. The count is the total
183number of bytes stored. The first byte stored is the length of the string, or
184255, whichever is smaller. The bytes of the string follow. If the string
185passed in to :func:`pack` is too long (longer than the count minus 1), only the
186leading count-1 bytes of the string are stored. If the string is shorter than
187count-1, it is padded with null bytes so that exactly count bytes in all are
188used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000189bytes, but that the string returned can never contain more than 255 bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000193For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl116aa622007-08-15 14:28:22 +0000194:const:`False`. When packing, the truth value of the argument object is used.
195Either 0 or 1 in the native or standard bool representation will be packed, and
196any non-zero value will be True when unpacking.
197
Mark Dickinson6abf1822010-04-12 21:00:59 +0000198
199.. _struct-alignment:
200
201Byte Order, Size, and Alignment
202^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
203
204By default, C types are represented in the machine's native format and byte
Georg Brandl116aa622007-08-15 14:28:22 +0000205order, and properly aligned by skipping pad bytes if necessary (according to the
206rules used by the C compiler).
207
208Alternatively, the first character of the format string can be used to indicate
209the byte order, size and alignment of the packed data, according to the
210following table:
211
212+-----------+------------------------+--------------------+
213| Character | Byte order | Size and alignment |
214+===========+========================+====================+
215| ``@`` | native | native |
216+-----------+------------------------+--------------------+
217| ``=`` | native | standard |
218+-----------+------------------------+--------------------+
219| ``<`` | little-endian | standard |
220+-----------+------------------------+--------------------+
221| ``>`` | big-endian | standard |
222+-----------+------------------------+--------------------+
223| ``!`` | network (= big-endian) | standard |
224+-----------+------------------------+--------------------+
225
226If the first character is not one of these, ``'@'`` is assumed.
227
Andrew M. Kuchlingfbd9d2f2010-02-22 15:15:21 +0000228Native byte order is big-endian or little-endian, depending on the host
229system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
230Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
231switchable endianness (bi-endian). Use ``sys.byteorder`` to check the
232endianness of your system.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234Native size and alignment are determined using the C compiler's
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000235``sizeof`` expression. This is always combined with native byte order.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237Standard size and alignment are as follows: no alignment is required for any
238type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
239:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
240bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
241point numbers, respectively. :ctype:`_Bool` is 1 byte.
242
243Note the difference between ``'@'`` and ``'='``: both use native byte order, but
244the size and alignment of the latter is standardized.
245
246The form ``'!'`` is available for those poor souls who claim they can't remember
247whether network byte order is big-endian or little-endian.
248
249There is no way to indicate non-native byte order (force byte-swapping); use the
250appropriate choice of ``'<'`` or ``'>'``.
251
252The ``'P'`` format character is only available for the native byte ordering
253(selected as the default or with the ``'@'`` byte order character). The byte
254order character ``'='`` chooses to use little- or big-endian ordering based on
255the host system. The struct module does not interpret this as native ordering,
256so the ``'P'`` format is not available.
257
Mark Dickinson6abf1822010-04-12 21:00:59 +0000258Notes:
259
260(1) Padding is only automatically added between successive structure members.
261 No padding is added at the beginning or the end of the encoded struct.
262
263(2) No padding is added when using non-native size and alignment, e.g.
264 with '<', '>', '=', and '!'.
265
266(3) To align the end of a structure to the alignment requirement of a
267 particular type, end the format with the code for that type with a repeat
268 count of zero. See :ref:`struct-examples`.
269
270
271.. _struct-examples:
272
273Examples
274^^^^^^^^
275
276.. note::
277 All examples assume a native byte order, size, and alignment with a
278 big-endian machine.
279
280A basic example of packing/unpacking three integers::
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282 >>> from struct import *
283 >>> pack('hhl', 1, 2, 3)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000284 b'\x00\x01\x00\x02\x00\x00\x00\x03'
285 >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
Georg Brandl116aa622007-08-15 14:28:22 +0000286 (1, 2, 3)
287 >>> calcsize('hhl')
288 8
289
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000290Unpacked fields can be named by assigning them to variables or by wrapping
291the result in a named tuple::
292
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000293 >>> record = b'raymond \x32\x12\x08\x01\x08'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000294 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
295
296 >>> from collections import namedtuple
297 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000298 >>> Student._make(unpack('<10sHHb', record))
299 Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Mark Dickinson6abf1822010-04-12 21:00:59 +0000301The ordering of format characters may have an impact on size since the padding
302needed to satisfy alignment requirements is different::
303
304 >>> pack('ci', '*', 0x12131415)
305 b'*\x00\x00\x00\x12\x13\x14\x15'
306 >>> pack('ic', 0x12131415, '*')
307 b'\x12\x13\x14\x15*'
308 >>> calcsize('ci')
309 8
310 >>> calcsize('ic')
311 5
312
313The following format ``'llh0l'`` specifies two pad bytes at the end, assuming
314longs are aligned on 4-byte boundaries::
315
316 >>> pack('llh0l', 1, 2, 3)
317 b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
318
319This only works when native size and alignment are in effect; standard size and
320alignment does not enforce any alignment.
321
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323.. seealso::
324
325 Module :mod:`array`
326 Packed binary storage of homogeneous data.
327
328 Module :mod:`xdrlib`
329 Packing and unpacking of XDR data.
330
331
332.. _struct-objects:
333
Mark Dickinson6abf1822010-04-12 21:00:59 +0000334Objects
335-------
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337The :mod:`struct` module also defines the following type:
338
339
340.. class:: Struct(format)
341
Mark Dickinson6abf1822010-04-12 21:00:59 +0000342 Return a new Struct object which writes and reads binary data according to
343 the format string *format*. Creating a Struct object once and calling its
344 methods is more efficient than calling the :mod:`struct` functions with the
345 same format since the format string only needs to be compiled once.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Benjamin Petersone41251e2008-04-25 01:59:09 +0000348 Compiled Struct objects support the following methods and attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Benjamin Petersone41251e2008-04-25 01:59:09 +0000350 .. method:: pack(v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Benjamin Petersone41251e2008-04-25 01:59:09 +0000352 Identical to the :func:`pack` function, using the compiled format.
353 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355
Benjamin Petersone41251e2008-04-25 01:59:09 +0000356 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000357
Benjamin Petersone41251e2008-04-25 01:59:09 +0000358 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000361 .. method:: unpack(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Benjamin Petersone41251e2008-04-25 01:59:09 +0000363 Identical to the :func:`unpack` function, using the compiled format.
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000364 (``len(bytes)`` must equal :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366
Georg Brandl7f01a132009-09-16 15:58:14 +0000367 .. method:: unpack_from(buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Benjamin Petersone41251e2008-04-25 01:59:09 +0000369 Identical to the :func:`unpack_from` function, using the compiled format.
370 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372
Benjamin Petersone41251e2008-04-25 01:59:09 +0000373 .. attribute:: format
Georg Brandl116aa622007-08-15 14:28:22 +0000374
Benjamin Petersone41251e2008-04-25 01:59:09 +0000375 The format string used to construct this Struct object.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Benjamin Petersone41251e2008-04-25 01:59:09 +0000377 .. attribute:: size
Guido van Rossum04110fb2007-08-24 16:32:05 +0000378
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000379 The calculated size of the struct (and hence of the bytes) corresponding
Benjamin Petersone41251e2008-04-25 01:59:09 +0000380 to :attr:`format`.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000381