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