Teks sumber — English
Terjemahan — Bahasa Indonesia
This module converts between Python values and C structs represented as Python :class:`bytes` objects. Compact :ref:`format strings <struct-format-strings>` describe the intended conversions to/from Python values. The module's functions and objects can be used for two largely distinct applications, data exchange with external sources (files or network connections), or data transfer between the Python application and the C layer.
Return a bytes object containing the values *v1*, *v2*, ... packed according to the format string *format*. The arguments must match the values required by the format exactly.
Pack the values *v1*, *v2*, ... according to the format string *format* and write the packed bytes into the writable buffer *buffer* starting at position *offset*. Note that *offset* is a required argument. A negative *offset* counts from the end of *buffer*.
Unpack from the buffer *buffer* (presumably packed by ``pack(format, ...)``) according to the format string *format*. The result is a tuple even if it contains exactly one item. The buffer's size in bytes must match the size required by the format, as reflected by :func:`calcsize`.
Unpack from *buffer* starting at position *offset*, according to the format string *format*. The result is a tuple even if it contains exactly one item. The buffer's size in bytes, starting at position *offset*, must be at least the size required by the format, as reflected by :func:`calcsize`. A negative *offset* counts from the end of *buffer*.
Iteratively unpack from the buffer *buffer* according to the format string *format*. This function returns an iterator which will read equally sized chunks from the buffer until all its contents have been consumed. The buffer's size in bytes must be a multiple of the size required by the format, as reflected by :func:`calcsize`.
Each iteration yields a tuple as specified by the format string.
Return the size of the struct (and hence of the bytes object produced by ``pack(format, ...)``) corresponding to the format string *format*.
Format Strings
Format strings describe the data layout when packing and unpacking data. They are built up from :ref:`type codes <type-codes>`, which specify the type of data being packed/unpacked. In addition, special characters control the :ref:`byte order, size and alignment<struct-alignment>`. Each format string consists of an optional prefix character which describes the overall properties of the data and one or more format characters which describe the actual data values and padding.
By default, C types are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). This behavior is chosen so that the bytes of a packed struct correspond exactly to the memory layout of the corresponding C struct. Whether to use native byte ordering and padding or standard formats depends on the application.
Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:
To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See :ref:`struct-examples`.
Type codes (or format codes) have the following meaning; the conversion between C and Python values should be obvious given their types. The 'Standard size' column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or ``'='``. When using native size, the size of the packed value is platform-dependent.
Format
Format
Added support for the ``'n'`` and ``'N'`` formats.
Added support for the ``'e'`` format.
Added support for the ``'F'`` and ``'D'`` formats.
Added support for the ``'Zf'`` and ``'Zd'`` formats. ``'F'`` and ``'D'`` formats are :term:`soft deprecated`.
The ``'n'`` and ``'N'`` conversion codes are only available for the native size (selected as the default or with the ``'@'`` byte order character). For the standard size, you can use whichever of the other integer formats fits your application.
For the ``'f'``, ``'d'`` and ``'e'`` conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for ``'f'``, ``'d'`` or ``'e'`` respectively), regardless of the floating-point format used by the platform.
The ``'P'`` type code is only available for the native byte ordering (selected as the default or with the ``'@'`` byte order character). The byte order character ``'='`` chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the ``'P'`` format is not available.
The IEEE 754 binary16 "half precision" type was introduced in the 2008 revision of the `IEEE 754 standard <ieee 754 standard_>`_. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately ``6.1e-05`` and ``6.5e+04`` at full precision. This type is not widely supported by C compilers: it's available as :c:expr:`_Float16` type, if the compiler supports the Annex H of the C23 standard. On a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the `half-precision floating-point format <half precision format_>`_ for more information.
For the ``'Zf'`` and ``'Zd'`` type codes, the packed representation uses the IEEE 754 binary32 and binary64 format for components of the complex number, regardless of the floating-point format used by the platform. Note that complex types are available unconditionally, despite complex types being an optional feature in C. As specified in the C11 standard, each complex type is represented by a two-element C array containing, respectively, the real and imaginary parts. The ``'F'`` and ``'D'`` (for ``'Zf'`` and ``'Zd'``, respectively) format characters are supported for compatibility.
A type code may be preceded by an integral repeat count. For example, the format string ``'4h'`` means exactly the same as ``'hhhh'``.
Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.
When packing a value ``x`` using one of the integer formats (``'b'``, ``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``, ``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format then :exc:`struct.error` is raised.
Previously, some of the integer formats wrapped out-of-range values and raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
Native byte order examples (designated by the ``'@'`` format prefix or lack of any prefix character) may not match what the reader's machine produces as that depends on the platform and compiler.
>>> pack(">h", 99999)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: 'h' format requires -32768 <= number <= 32767
Demonstrate the difference between ``'s'`` and ``'c'`` format characters::
The following format ``'llh0l'`` results in two pad bytes being added at the end, assuming the platform's longs are aligned on 4-byte boundaries::
Two main applications for the :mod:`!struct` module exist, data interchange between Python and C code within an application or another application compiled using the same compiler (:ref:`native formats<struct-native-formats>`), and data interchange between applications using agreed upon data layout (:ref:`standard formats<struct-standard-formats>`). Generally speaking, the format strings constructed for these two domains are distinct.
Native Formats
When constructing format strings which mimic native layouts, the compiler and machine architecture determine byte ordering and padding. In such cases, the ``@`` format character should be used to specify native byte ordering and data sizes. Internal pad bytes are normally inserted automatically. It is possible that a zero-repeat type code will be needed at the end of a format string to round up to the correct byte boundary for proper alignment of consecutive chunks of data.
Data is not padded to an 8-byte boundary at the end of the second format string without the use of extra padding. A zero-repeat format code solves that problem::
The ``'x'`` type code can be used to specify the repeat, but for native formats it is better to use a zero-repeat format like ``'0l'``.
Standard Formats
When exchanging data beyond your process such as networking or storage, be precise. Specify the exact byte order, size, and alignment. Do not assume they match the native order of a particular machine. For example, network byte order is big-endian, while many popular CPUs are little-endian. By defining this explicitly, the user need not care about the specifics of the platform their code is running on. The first character should typically be ``<`` or ``>`` (or ``!``). Padding is the responsibility of the programmer. The zero-repeat format character won't work. Instead, the user must explicitly add ``'x'`` pad bytes where needed. Revisiting the examples from the previous section, we have::
Return a new Struct object which writes and reads binary data according to the format string *format*. Creating a ``Struct`` object once and calling its methods is more efficient than calling module-level functions with the same format since the format string is only compiled once.
The compiled versions of the most recent format strings passed to the module-level functions are cached, so programs that use only a few format strings needn't worry about reusing a single :class:`Struct` instance.
Identical to the :func:`pack` function, using the compiled format. (``len(result)`` will equal :attr:`size`.)
Identical to the :func:`pack_into` function, using the compiled format.
Identical to the :func:`unpack` function, using the compiled format. The buffer's size in bytes must equal :attr:`size`.
Identical to the :func:`unpack_from` function, using the compiled format. The buffer's size in bytes, starting at position *offset*, must be at least :attr:`size`.
Identical to the :func:`iter_unpack` function, using the compiled format. The buffer's size in bytes must be a multiple of :attr:`size`.
The format string used to construct this Struct object.
The format string type is now :class:`str` instead of :class:`bytes`.
The calculated size of the struct (and hence of the bytes object produced by the :meth:`pack` method) corresponding to :attr:`format`.
in struct format strings