1:mod:`struct` --- Interpret bytes as packed binary data
2=======================================================
3
4.. module:: struct
5   :synopsis: Interpret bytes as packed binary data.
6
7**Source code:** :source:`Lib/struct.py`
8
9.. index::
10   pair: C; structures
11   triple: packing; binary; data
12
13--------------
14
15This module converts between Python values and C structs represented
16as Python :class:`bytes` objects.  Compact :ref:`format strings <struct-format-strings>`
17describe the intended conversions to/from Python values.
18The module's functions and objects can be used for two largely
19distinct applications, data exchange with external sources (files or
20network connections), or data transfer between the Python application
21and the C layer.
22
23.. note::
24
25   When no prefix character is given, native mode is the default. It
26   packs or unpacks data based on the platform and compiler on which
27   the Python interpreter was built.
28   The result of packing a given C struct includes pad bytes which
29   maintain proper alignment for the C types involved; similarly,
30   alignment is taken into account when unpacking.  In contrast, when
31   communicating data between external sources, the programmer is
32   responsible for defining byte ordering and padding between elements.
33   See :ref:`struct-alignment` for details.
34
35Several :mod:`struct` functions (and methods of :class:`Struct`) take a *buffer*
36argument.  This refers to objects that implement the :ref:`bufferobjects` and
37provide either a readable or read-writable buffer.  The most common types used
38for that purpose are :class:`bytes` and :class:`bytearray`, but many other types
39that can be viewed as an array of bytes implement the buffer protocol, so that
40they can be read/filled without additional copying from a :class:`bytes` object.
41
42
43Functions and Exceptions
44------------------------
45
46The module defines the following exception and functions:
47
48
49.. exception:: error
50
51   Exception raised on various occasions; argument is a string describing what
52   is wrong.
53
54
55.. function:: pack(format, v1, v2, ...)
56
57   Return a bytes object containing the values *v1*, *v2*, ... packed according
58   to the format string *format*.  The arguments must match the values required by
59   the format exactly.
60
61
62.. function:: pack_into(format, buffer, offset, v1, v2, ...)
63
64   Pack the values *v1*, *v2*, ... according to the format string *format* and
65   write the packed bytes into the writable buffer *buffer* starting at
66   position *offset*.  Note that *offset* is a required argument.
67
68
69.. function:: unpack(format, buffer)
70
71   Unpack from the buffer *buffer* (presumably packed by ``pack(format, ...)``)
72   according to the format string *format*.  The result is a tuple even if it
73   contains exactly one item.  The buffer's size in bytes must match the
74   size required by the format, as reflected by :func:`calcsize`.
75
76
77.. function:: unpack_from(format, /, buffer, offset=0)
78
79   Unpack from *buffer* starting at position *offset*, according to the format
80   string *format*.  The result is a tuple even if it contains exactly one
81   item.  The buffer's size in bytes, starting at position *offset*, must be at
82   least the size required by the format, as reflected by :func:`calcsize`.
83
84
85.. function:: iter_unpack(format, buffer)
86
87   Iteratively unpack from the buffer *buffer* according to the format
88   string *format*.  This function returns an iterator which will read
89   equally sized chunks from the buffer until all its contents have been
90   consumed.  The buffer's size in bytes must be a multiple of the size
91   required by the format, as reflected by :func:`calcsize`.
92
93   Each iteration yields a tuple as specified by the format string.
94
95   .. versionadded:: 3.4
96
97
98.. function:: calcsize(format)
99
100   Return the size of the struct (and hence of the bytes object produced by
101   ``pack(format, ...)``) corresponding to the format string *format*.
102
103
104.. _struct-format-strings:
105
106Format Strings
107--------------
108
109Format strings describe the data layout when
110packing and unpacking data.  They are built up from :ref:`format characters<format-characters>`,
111which specify the type of data being packed/unpacked.  In addition,
112special characters control the :ref:`byte order, size and alignment<struct-alignment>`.
113Each format string consists of an optional prefix character which
114describes the overall properties of the data and one or more format
115characters which describe the actual data values and padding.
116
117
118.. _struct-alignment:
119
120Byte Order, Size, and Alignment
121^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
122
123By default, C types are represented in the machine's native format and byte
124order, and properly aligned by skipping pad bytes if necessary (according to the
125rules used by the C compiler).
126This behavior is chosen so
127that the bytes of a packed struct correspond exactly to the memory layout
128of the corresponding C struct.
129Whether to use native byte ordering
130and padding or standard formats depends on the application.
131
132.. index::
133   single: @ (at); in struct format strings
134   single: = (equals); in struct format strings
135   single: < (less); in struct format strings
136   single: > (greater); in struct format strings
137   single: ! (exclamation); in struct format strings
138
139Alternatively, the first character of the format string can be used to indicate
140the byte order, size and alignment of the packed data, according to the
141following table:
142
143+-----------+------------------------+----------+-----------+
144| Character | Byte order             | Size     | Alignment |
145+===========+========================+==========+===========+
146| ``@``     | native                 | native   | native    |
147+-----------+------------------------+----------+-----------+
148| ``=``     | native                 | standard | none      |
149+-----------+------------------------+----------+-----------+
150| ``<``     | little-endian          | standard | none      |
151+-----------+------------------------+----------+-----------+
152| ``>``     | big-endian             | standard | none      |
153+-----------+------------------------+----------+-----------+
154| ``!``     | network (= big-endian) | standard | none      |
155+-----------+------------------------+----------+-----------+
156
157If the first character is not one of these, ``'@'`` is assumed.
158
159Native byte order is big-endian or little-endian, depending on the
160host system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are
161little-endian; IBM z and many legacy architectures are big-endian.
162Use :data:`sys.byteorder` to check the endianness of your system.
163
164Native size and alignment are determined using the C compiler's
165``sizeof`` expression.  This is always combined with native byte order.
166
167Standard size depends only on the format character;  see the table in
168the :ref:`format-characters` section.
169
170Note the difference between ``'@'`` and ``'='``: both use native byte order, but
171the size and alignment of the latter is standardized.
172
173The form ``'!'`` represents the network byte order which is always big-endian
174as defined in `IETF RFC 1700 <IETF RFC 1700_>`_.
175
176There is no way to indicate non-native byte order (force byte-swapping); use the
177appropriate choice of ``'<'`` or ``'>'``.
178
179Notes:
180
181(1) Padding is only automatically added between successive structure members.
182    No padding is added at the beginning or the end of the encoded struct.
183
184(2) No padding is added when using non-native size and alignment, e.g.
185    with '<', '>', '=', and '!'.
186
187(3) To align the end of a structure to the alignment requirement of a
188    particular type, end the format with the code for that type with a repeat
189    count of zero.  See :ref:`struct-examples`.
190
191
192.. _format-characters:
193
194Format Characters
195^^^^^^^^^^^^^^^^^
196
197Format characters have the following meaning; the conversion between C and
198Python values should be obvious given their types.  The 'Standard size' column
199refers to the size of the packed value in bytes when using standard size; that
200is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or
201``'='``.  When using native size, the size of the packed value is
202platform-dependent.
203
204+--------+--------------------------+--------------------+----------------+------------+
205| Format | C Type                   | Python type        | Standard size  | Notes      |
206+========+==========================+====================+================+============+
207| ``x``  | pad byte                 | no value           |                | \(7)       |
208+--------+--------------------------+--------------------+----------------+------------+
209| ``c``  | :c:expr:`char`           | bytes of length 1  | 1              |            |
210+--------+--------------------------+--------------------+----------------+------------+
211| ``b``  | :c:expr:`signed char`    | integer            | 1              | \(1), \(2) |
212+--------+--------------------------+--------------------+----------------+------------+
213| ``B``  | :c:expr:`unsigned char`  | integer            | 1              | \(2)       |
214+--------+--------------------------+--------------------+----------------+------------+
215| ``?``  | :c:expr:`_Bool`          | bool               | 1              | \(1)       |
216+--------+--------------------------+--------------------+----------------+------------+
217| ``h``  | :c:expr:`short`          | integer            | 2              | \(2)       |
218+--------+--------------------------+--------------------+----------------+------------+
219| ``H``  | :c:expr:`unsigned short` | integer            | 2              | \(2)       |
220+--------+--------------------------+--------------------+----------------+------------+
221| ``i``  | :c:expr:`int`            | integer            | 4              | \(2)       |
222+--------+--------------------------+--------------------+----------------+------------+
223| ``I``  | :c:expr:`unsigned int`   | integer            | 4              | \(2)       |
224+--------+--------------------------+--------------------+----------------+------------+
225| ``l``  | :c:expr:`long`           | integer            | 4              | \(2)       |
226+--------+--------------------------+--------------------+----------------+------------+
227| ``L``  | :c:expr:`unsigned long`  | integer            | 4              | \(2)       |
228+--------+--------------------------+--------------------+----------------+------------+
229| ``q``  | :c:expr:`long long`      | integer            | 8              | \(2)       |
230+--------+--------------------------+--------------------+----------------+------------+
231| ``Q``  | :c:expr:`unsigned long   | integer            | 8              | \(2)       |
232|        | long`                    |                    |                |            |
233+--------+--------------------------+--------------------+----------------+------------+
234| ``n``  | :c:expr:`ssize_t`        | integer            |                | \(3)       |
235+--------+--------------------------+--------------------+----------------+------------+
236| ``N``  | :c:expr:`size_t`         | integer            |                | \(3)       |
237+--------+--------------------------+--------------------+----------------+------------+
238| ``e``  | \(6)                     | float              | 2              | \(4)       |
239+--------+--------------------------+--------------------+----------------+------------+
240| ``f``  | :c:expr:`float`          | float              | 4              | \(4)       |
241+--------+--------------------------+--------------------+----------------+------------+
242| ``d``  | :c:expr:`double`         | float              | 8              | \(4)       |
243+--------+--------------------------+--------------------+----------------+------------+
244| ``s``  | :c:expr:`char[]`         | bytes              |                | \(9)       |
245+--------+--------------------------+--------------------+----------------+------------+
246| ``p``  | :c:expr:`char[]`         | bytes              |                | \(8)       |
247+--------+--------------------------+--------------------+----------------+------------+
248| ``P``  | :c:expr:`void \*`        | integer            |                | \(5)       |
249+--------+--------------------------+--------------------+----------------+------------+
250
251.. versionchanged:: 3.3
252   Added support for the ``'n'`` and ``'N'`` formats.
253
254.. versionchanged:: 3.6
255   Added support for the ``'e'`` format.
256
257
258Notes:
259
260(1)
261   .. index:: single: ? (question mark); in struct format strings
262
263   The ``'?'`` conversion code corresponds to the :c:expr:`_Bool` type defined by
264   C99. If this type is not available, it is simulated using a :c:expr:`char`. In
265   standard mode, it is always represented by one byte.
266
267(2)
268   When attempting to pack a non-integer using any of the integer conversion
269   codes, if the non-integer has a :meth:`__index__` method then that method is
270   called to convert the argument to an integer before packing.
271
272   .. versionchanged:: 3.2
273      Added use of the :meth:`__index__` method for non-integers.
274
275(3)
276   The ``'n'`` and ``'N'`` conversion codes are only available for the native
277   size (selected as the default or with the ``'@'`` byte order character).
278   For the standard size, you can use whichever of the other integer formats
279   fits your application.
280
281(4)
282   For the ``'f'``, ``'d'`` and ``'e'`` conversion codes, the packed
283   representation uses the IEEE 754 binary32, binary64 or binary16 format (for
284   ``'f'``, ``'d'`` or ``'e'`` respectively), regardless of the floating-point
285   format used by the platform.
286
287(5)
288   The ``'P'`` format character is only available for the native byte ordering
289   (selected as the default or with the ``'@'`` byte order character). The byte
290   order character ``'='`` chooses to use little- or big-endian ordering based
291   on the host system. The struct module does not interpret this as native
292   ordering, so the ``'P'`` format is not available.
293
294(6)
295   The IEEE 754 binary16 "half precision" type was introduced in the 2008
296   revision of the `IEEE 754 standard <ieee 754 standard_>`_. It has a sign
297   bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored),
298   and can represent numbers between approximately ``6.1e-05`` and ``6.5e+04``
299   at full precision. This type is not widely supported by C compilers: on a
300   typical machine, an unsigned short can be used for storage, but not for math
301   operations. See the Wikipedia page on the `half-precision floating-point
302   format <half precision format_>`_ for more information.
303
304(7)
305   When packing, ``'x'`` inserts one NUL byte.
306
307(8)
308   The ``'p'`` format character encodes a "Pascal string", meaning a short
309   variable-length string stored in a *fixed number of bytes*, given by the count.
310   The first byte stored is the length of the string, or 255, whichever is
311   smaller.  The bytes of the string follow.  If the string passed in to
312   :func:`pack` is too long (longer than the count minus 1), only the leading
313   ``count-1`` bytes of the string are stored.  If the string is shorter than
314   ``count-1``, it is padded with null bytes so that exactly count bytes in all
315   are used.  Note that for :func:`unpack`, the ``'p'`` format character consumes
316   ``count`` bytes, but that the string returned can never contain more than 255
317   bytes.
318
319(9)
320   For the ``'s'`` format character, the count is interpreted as the length of the
321   bytes, not a repeat count like for the other format characters; for example,
322   ``'10s'`` means a single 10-byte string mapping to or from a single
323   Python byte string, while ``'10c'`` means 10
324   separate one byte character elements (e.g., ``cccccccccc``) mapping
325   to or from ten different Python byte objects. (See :ref:`struct-examples`
326   for a concrete demonstration of the difference.)
327   If a count is not given, it defaults to 1.  For packing, the string is
328   truncated or padded with null bytes as appropriate to make it fit. For
329   unpacking, the resulting bytes object always has exactly the specified number
330   of bytes.  As a special case, ``'0s'`` means a single, empty string (while
331   ``'0c'`` means 0 characters).
332
333A format character may be preceded by an integral repeat count.  For example,
334the format string ``'4h'`` means exactly the same as ``'hhhh'``.
335
336Whitespace characters between formats are ignored; a count and its format must
337not contain whitespace though.
338
339When packing a value ``x`` using one of the integer formats (``'b'``,
340``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``,
341``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format
342then :exc:`struct.error` is raised.
343
344.. versionchanged:: 3.1
345   Previously, some of the integer formats wrapped out-of-range values and
346   raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
347
348.. index:: single: ? (question mark); in struct format strings
349
350For the ``'?'`` format character, the return value is either :const:`True` or
351:const:`False`. When packing, the truth value of the argument object is used.
352Either 0 or 1 in the native or standard bool representation will be packed, and
353any non-zero value will be ``True`` when unpacking.
354
355
356
357.. _struct-examples:
358
359Examples
360^^^^^^^^
361
362.. note::
363   Native byte order examples (designated by the ``'@'`` format prefix or
364   lack of any prefix character) may not match what the reader's
365   machine produces as
366   that depends on the platform and compiler.
367
368Pack and unpack integers of three different sizes, using big endian
369ordering::
370
371    >>> from struct import *
372    >>> pack(">bhl", 1, 2, 3)
373    b'\x01\x00\x02\x00\x00\x00\x03'
374    >>> unpack('>bhl', b'\x01\x00\x02\x00\x00\x00\x03')
375    (1, 2, 3)
376    >>> calcsize('>bhl')
377    7
378
379Attempt to pack an integer which is too large for the defined field::
380
381    >>> pack(">h", 99999)
382    Traceback (most recent call last):
383      File "<stdin>", line 1, in <module>
384    struct.error: 'h' format requires -32768 <= number <= 32767
385
386Demonstrate the difference between ``'s'`` and ``'c'`` format
387characters::
388
389    >>> pack("@ccc", b'1', b'2', b'3')
390    b'123'
391    >>> pack("@3s", b'123')
392    b'123'
393
394Unpacked fields can be named by assigning them to variables or by wrapping
395the result in a named tuple::
396
397    >>> record = b'raymond   \x32\x12\x08\x01\x08'
398    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
399
400    >>> from collections import namedtuple
401    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
402    >>> Student._make(unpack('<10sHHb', record))
403    Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)
404
405The ordering of format characters may have an impact on size in native
406mode since padding is implicit. In standard mode, the user is
407responsible for inserting any desired padding.
408Note in
409the first ``pack`` call below that three NUL bytes were added after the
410packed ``'#'`` to align the following integer on a four-byte boundary.
411In this example, the output was produced on a little endian machine::
412
413    >>> pack('@ci', b'#', 0x12131415)
414    b'#\x00\x00\x00\x15\x14\x13\x12'
415    >>> pack('@ic', 0x12131415, b'#')
416    b'\x15\x14\x13\x12#'
417    >>> calcsize('@ci')
418    8
419    >>> calcsize('@ic')
420    5
421
422The following format ``'llh0l'`` results in two pad bytes being added
423at the end, assuming the platform's longs are aligned on 4-byte boundaries::
424
425    >>> pack('@llh0l', 1, 2, 3)
426    b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
427
428
429.. seealso::
430
431   Module :mod:`array`
432      Packed binary storage of homogeneous data.
433
434   Module :mod:`json`
435      JSON encoder and decoder.
436
437   Module :mod:`pickle`
438      Python object serialization.
439
440
441.. _applications:
442
443Applications
444------------
445
446Two main applications for the :mod:`struct` module exist, data
447interchange between Python and C code within an application or another
448application compiled using the same compiler (:ref:`native formats<struct-native-formats>`), and
449data interchange between applications using agreed upon data layout
450(:ref:`standard formats<struct-standard-formats>`).  Generally speaking, the format strings
451constructed for these two domains are distinct.
452
453
454.. _struct-native-formats:
455
456Native Formats
457^^^^^^^^^^^^^^
458
459When constructing format strings which mimic native layouts, the
460compiler and machine architecture determine byte ordering and padding.
461In such cases, the ``@`` format character should be used to specify
462native byte ordering and data sizes.  Internal pad bytes are normally inserted
463automatically.  It is possible that a zero-repeat format code will be
464needed at the end of a format string to round up to the correct
465byte boundary for proper alignment of consective chunks of data.
466
467Consider these two simple examples (on a 64-bit, little-endian
468machine)::
469
470    >>> calcsize('@lhl')
471    24
472    >>> calcsize('@llh')
473    18
474
475Data is not padded to an 8-byte boundary at the end of the second
476format string without the use of extra padding.  A zero-repeat format
477code solves that problem::
478
479    >>> calcsize('@llh0l')
480    24
481
482The ``'x'`` format code can be used to specify the repeat, but for
483native formats it is better to use a zero-repeat format like ``'0l'``.
484
485By default, native byte ordering and alignment is used, but it is
486better to be explicit and use the ``'@'`` prefix character.
487
488
489.. _struct-standard-formats:
490
491Standard Formats
492^^^^^^^^^^^^^^^^
493
494When exchanging data beyond your process such as networking or storage,
495be precise.  Specify the exact byte order, size, and alignment.  Do
496not assume they match the native order of a particular machine.
497For example, network byte order is big-endian, while many popular CPUs
498are little-endian.  By defining this explicitly, the user need not
499care about the specifics of the platform their code is running on.
500The first character should typically be ``<`` or ``>``
501(or ``!``).  Padding is the responsibility of the programmer.  The
502zero-repeat format character won't work.  Instead, the user must
503explicitly add ``'x'`` pad bytes where needed.  Revisiting the
504examples from the previous section, we have::
505
506    >>> calcsize('<qh6xq')
507    24
508    >>> pack('<qh6xq', 1, 2, 3) == pack('@lhl', 1, 2, 3)
509    True
510    >>> calcsize('@llh')
511    18
512    >>> pack('@llh', 1, 2, 3) == pack('<qqh', 1, 2, 3)
513    True
514    >>> calcsize('<qqh6x')
515    24
516    >>> calcsize('@llh0l')
517    24
518    >>> pack('@llh0l', 1, 2, 3) == pack('<qqh6x', 1, 2, 3)
519    True
520
521The above results (executed on a 64-bit machine) aren't guaranteed to
522match when executed on different machines.  For example, the examples
523below were executed on a 32-bit machine::
524
525    >>> calcsize('<qqh6x')
526    24
527    >>> calcsize('@llh0l')
528    12
529    >>> pack('@llh0l', 1, 2, 3) == pack('<qqh6x', 1, 2, 3)
530    False
531
532
533.. _struct-objects:
534
535Classes
536-------
537
538The :mod:`struct` module also defines the following type:
539
540
541.. class:: Struct(format)
542
543   Return a new Struct object which writes and reads binary data according to
544   the format string *format*.  Creating a ``Struct`` object once and calling its
545   methods is more efficient than calling module-level functions with the
546   same format since the format string is only compiled once.
547
548   .. note::
549
550      The compiled versions of the most recent format strings passed to
551      :class:`Struct` and the module-level functions are cached, so programs
552      that use only a few format strings needn't worry about reusing a single
553      :class:`Struct` instance.
554
555   Compiled Struct objects support the following methods and attributes:
556
557   .. method:: pack(v1, v2, ...)
558
559      Identical to the :func:`pack` function, using the compiled format.
560      (``len(result)`` will equal :attr:`size`.)
561
562
563   .. method:: pack_into(buffer, offset, v1, v2, ...)
564
565      Identical to the :func:`pack_into` function, using the compiled format.
566
567
568   .. method:: unpack(buffer)
569
570      Identical to the :func:`unpack` function, using the compiled format.
571      The buffer's size in bytes must equal :attr:`size`.
572
573
574   .. method:: unpack_from(buffer, offset=0)
575
576      Identical to the :func:`unpack_from` function, using the compiled format.
577      The buffer's size in bytes, starting at position *offset*, must be at least
578      :attr:`size`.
579
580
581   .. method:: iter_unpack(buffer)
582
583      Identical to the :func:`iter_unpack` function, using the compiled format.
584      The buffer's size in bytes must be a multiple of :attr:`size`.
585
586      .. versionadded:: 3.4
587
588   .. attribute:: format
589
590      The format string used to construct this Struct object.
591
592      .. versionchanged:: 3.7
593         The format string type is now :class:`str` instead of :class:`bytes`.
594
595   .. attribute:: size
596
597      The calculated size of the struct (and hence of the bytes object produced
598      by the :meth:`pack` method) corresponding to :attr:`format`.
599
600
601.. _half precision format: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
602
603.. _ieee 754 standard: https://en.wikipedia.org/wiki/IEEE_754-2008_revision
604
605.. _IETF RFC 1700: https://datatracker.ietf.org/doc/html/rfc1700
606