blob: da8cc04573ea67e65c50c46b369f7b80b3e6df9b [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
Benjamin Peterson4ae19462008-07-31 15:03:40 +000012as Python :class:`bytes` objects. It uses :dfn:`format strings` (explained
13below) as compact descriptions of the lay-out of the C structs and the
14intended conversion to/from Python values. This can be used in handling
15binary data stored in files or from network connections, among other sources.
Georg Brandl116aa622007-08-15 14:28:22 +000016
17The module defines the following exception and functions:
18
19
20.. exception:: error
21
22 Exception raised on various occasions; argument is a string describing what is
23 wrong.
24
25
26.. function:: pack(fmt, v1, v2, ...)
27
Benjamin Peterson4ae19462008-07-31 15:03:40 +000028 Return a bytes containing the values ``v1, v2, ...`` packed according to the
Georg Brandl116aa622007-08-15 14:28:22 +000029 given format. The arguments must match the values required by the format
30 exactly.
31
32
33.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
34
35 Pack the values ``v1, v2, ...`` according to the given format, write the packed
36 bytes into the writable *buffer* starting at *offset*. Note that the offset is
37 a required argument.
38
Georg Brandl116aa622007-08-15 14:28:22 +000039
Benjamin Peterson4ae19462008-07-31 15:03:40 +000040.. function:: unpack(fmt, bytes)
Georg Brandl116aa622007-08-15 14:28:22 +000041
Benjamin Peterson4ae19462008-07-31 15:03:40 +000042 Unpack the bytes (presumably packed by ``pack(fmt, ...)``) according to the
Georg Brandl116aa622007-08-15 14:28:22 +000043 given format. The result is a tuple even if it contains exactly one item. The
Benjamin Peterson4ae19462008-07-31 15:03:40 +000044 bytes must contain exactly the amount of data required by the format
45 (``len(bytes)`` must equal ``calcsize(fmt)``).
Georg Brandl116aa622007-08-15 14:28:22 +000046
47
Georg Brandl7f01a132009-09-16 15:58:14 +000048.. function:: unpack_from(fmt, buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +000049
Benjamin Petersone0124bd2009-03-09 21:04:33 +000050 Unpack the *buffer* according to the given format. The result is a tuple even
Georg Brandl116aa622007-08-15 14:28:22 +000051 if it contains exactly one item. The *buffer* must contain at least the amount
52 of data required by the format (``len(buffer[offset:])`` must be at least
53 ``calcsize(fmt)``).
54
Georg Brandl116aa622007-08-15 14:28:22 +000055
56.. function:: calcsize(fmt)
57
Benjamin Peterson4ae19462008-07-31 15:03:40 +000058 Return the size of the struct (and hence of the bytes) corresponding to the
Georg Brandl116aa622007-08-15 14:28:22 +000059 given format.
60
61Format characters have the following meaning; the conversion between C and
62Python values should be obvious given their types:
63
64+--------+-------------------------+--------------------+-------+
65| Format | C Type | Python | Notes |
66+========+=========================+====================+=======+
67| ``x`` | pad byte | no value | |
68+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000069| ``c`` | :ctype:`char` | bytes of length 1 | |
Georg Brandl116aa622007-08-15 14:28:22 +000070+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000071| ``b`` | :ctype:`signed char` | integer | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +000072+--------+-------------------------+--------------------+-------+
73| ``B`` | :ctype:`unsigned char` | integer | |
74+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000075| ``?`` | :ctype:`_Bool` | bool | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +000076+--------+-------------------------+--------------------+-------+
77| ``h`` | :ctype:`short` | integer | |
78+--------+-------------------------+--------------------+-------+
79| ``H`` | :ctype:`unsigned short` | integer | |
80+--------+-------------------------+--------------------+-------+
81| ``i`` | :ctype:`int` | integer | |
82+--------+-------------------------+--------------------+-------+
Georg Brandlba956ae2007-11-29 17:24:34 +000083| ``I`` | :ctype:`unsigned int` | integer | |
Georg Brandl116aa622007-08-15 14:28:22 +000084+--------+-------------------------+--------------------+-------+
85| ``l`` | :ctype:`long` | integer | |
86+--------+-------------------------+--------------------+-------+
Georg Brandlba956ae2007-11-29 17:24:34 +000087| ``L`` | :ctype:`unsigned long` | integer | |
Georg Brandl116aa622007-08-15 14:28:22 +000088+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000089| ``q`` | :ctype:`long long` | integer | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +000090+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000091| ``Q`` | :ctype:`unsigned long | integer | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +000092| | long` | | |
93+--------+-------------------------+--------------------+-------+
94| ``f`` | :ctype:`float` | float | |
95+--------+-------------------------+--------------------+-------+
96| ``d`` | :ctype:`double` | float | |
97+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +000098| ``s`` | :ctype:`char[]` | bytes | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +000099+--------+-------------------------+--------------------+-------+
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000100| ``p`` | :ctype:`char[]` | bytes | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +0000101+--------+-------------------------+--------------------+-------+
102| ``P`` | :ctype:`void \*` | integer | |
103+--------+-------------------------+--------------------+-------+
104
105Notes:
106
107(1)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000108 The ``c``, ``s`` and ``p`` conversion codes operate on :class:`bytes`
109 objects, but packing with such codes also supports :class:`str` objects,
110 which are encoded using UTF-8.
111
112(2)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000113 The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
Georg Brandl116aa622007-08-15 14:28:22 +0000114 C99. If this type is not available, it is simulated using a :ctype:`char`. In
115 standard mode, it is always represented by one byte.
116
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000117(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000118 The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
119 the platform C compiler supports C :ctype:`long long`, or, on Windows,
120 :ctype:`__int64`. They are always available in standard modes.
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122A format character may be preceded by an integral repeat count. For example,
123the format string ``'4h'`` means exactly the same as ``'hhhh'``.
124
125Whitespace characters between formats are ignored; a count and its format must
126not contain whitespace though.
127
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000128For the ``'s'`` format character, the count is interpreted as the length of the
129bytes, not a repeat count like for the other format characters; for example,
Georg Brandl116aa622007-08-15 14:28:22 +0000130``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
131For packing, the string is truncated or padded with null bytes as appropriate to
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000132make it fit. For unpacking, the resulting bytes object always has exactly the
Georg Brandl116aa622007-08-15 14:28:22 +0000133specified number of bytes. As a special case, ``'0s'`` means a single, empty
134string (while ``'0c'`` means 0 characters).
135
Mark Dickinsonb40b9472009-03-29 16:58:21 +0000136When packing a value ``x`` using one of the integer formats (``'b'``,
137``'B'``, ``'h'``, ``'H'``, ``'i'``, ``'I'``, ``'l'``, ``'L'``,
138``'q'``, ``'Q'``), if ``x`` is outside the valid range for that format
139then :exc:`struct.error` is raised.
140
141.. versionchanged:: 3.1
142 In 3.0, some of the integer formats wrapped out-of-range values and
143 raised :exc:`DeprecationWarning` instead of :exc:`struct.error`.
144
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146The ``'p'`` format character encodes a "Pascal string", meaning a short
147variable-length string stored in a fixed number of bytes. The count is the total
148number of bytes stored. The first byte stored is the length of the string, or
149255, whichever is smaller. The bytes of the string follow. If the string
150passed in to :func:`pack` is too long (longer than the count minus 1), only the
151leading count-1 bytes of the string are stored. If the string is shorter than
152count-1, it is padded with null bytes so that exactly count bytes in all are
153used. Note that for :func:`unpack`, the ``'p'`` format character consumes count
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000154bytes, but that the string returned can never contain more than 255 bytes.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000158For the ``'?'`` format character, the return value is either :const:`True` or
Georg Brandl116aa622007-08-15 14:28:22 +0000159:const:`False`. When packing, the truth value of the argument object is used.
160Either 0 or 1 in the native or standard bool representation will be packed, and
161any non-zero value will be True when unpacking.
162
163By default, C numbers are represented in the machine's native format and byte
164order, and properly aligned by skipping pad bytes if necessary (according to the
165rules used by the C compiler).
166
167Alternatively, the first character of the format string can be used to indicate
168the byte order, size and alignment of the packed data, according to the
169following table:
170
171+-----------+------------------------+--------------------+
172| Character | Byte order | Size and alignment |
173+===========+========================+====================+
174| ``@`` | native | native |
175+-----------+------------------------+--------------------+
176| ``=`` | native | standard |
177+-----------+------------------------+--------------------+
178| ``<`` | little-endian | standard |
179+-----------+------------------------+--------------------+
180| ``>`` | big-endian | standard |
181+-----------+------------------------+--------------------+
182| ``!`` | network (= big-endian) | standard |
183+-----------+------------------------+--------------------+
184
185If the first character is not one of these, ``'@'`` is assumed.
186
187Native byte order is big-endian or little-endian, depending on the host system.
188For example, Motorola and Sun processors are big-endian; Intel and DEC
189processors are little-endian.
190
191Native size and alignment are determined using the C compiler's
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000192``sizeof`` expression. This is always combined with native byte order.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194Standard size and alignment are as follows: no alignment is required for any
195type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
196:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
197bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
198point numbers, respectively. :ctype:`_Bool` is 1 byte.
199
200Note the difference between ``'@'`` and ``'='``: both use native byte order, but
201the size and alignment of the latter is standardized.
202
203The form ``'!'`` is available for those poor souls who claim they can't remember
204whether network byte order is big-endian or little-endian.
205
206There is no way to indicate non-native byte order (force byte-swapping); use the
207appropriate choice of ``'<'`` or ``'>'``.
208
209The ``'P'`` format character is only available for the native byte ordering
210(selected as the default or with the ``'@'`` byte order character). The byte
211order character ``'='`` chooses to use little- or big-endian ordering based on
212the host system. The struct module does not interpret this as native ordering,
213so the ``'P'`` format is not available.
214
215Examples (all using native byte order, size and alignment, on a big-endian
216machine)::
217
218 >>> from struct import *
219 >>> pack('hhl', 1, 2, 3)
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000220 b'\x00\x01\x00\x02\x00\x00\x00\x03'
221 >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
Georg Brandl116aa622007-08-15 14:28:22 +0000222 (1, 2, 3)
223 >>> calcsize('hhl')
224 8
225
226Hint: to align the end of a structure to the alignment requirement of a
227particular type, end the format with the code for that type with a repeat count
228of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the
229end, assuming longs are aligned on 4-byte boundaries. This only works when
230native size and alignment are in effect; standard size and alignment does not
231enforce any alignment.
232
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000233Unpacked fields can be named by assigning them to variables or by wrapping
234the result in a named tuple::
235
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000236 >>> record = b'raymond \x32\x12\x08\x01\x08'
Benjamin Peterson2b7411d2008-05-26 17:36:47 +0000237 >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
238
239 >>> from collections import namedtuple
240 >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000241 >>> Student._make(unpack('<10sHHb', record))
242 Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244.. seealso::
245
246 Module :mod:`array`
247 Packed binary storage of homogeneous data.
248
249 Module :mod:`xdrlib`
250 Packing and unpacking of XDR data.
251
252
253.. _struct-objects:
254
255Struct Objects
256--------------
257
258The :mod:`struct` module also defines the following type:
259
260
261.. class:: Struct(format)
262
263 Return a new Struct object which writes and reads binary data according to the
264 format string *format*. Creating a Struct object once and calling its methods
265 is more efficient than calling the :mod:`struct` functions with the same format
266 since the format string only needs to be compiled once.
267
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Benjamin Petersone41251e2008-04-25 01:59:09 +0000269 Compiled Struct objects support the following methods and attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Benjamin Petersone41251e2008-04-25 01:59:09 +0000271 .. method:: pack(v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Benjamin Petersone41251e2008-04-25 01:59:09 +0000273 Identical to the :func:`pack` function, using the compiled format.
274 (``len(result)`` will equal :attr:`self.size`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276
Benjamin Petersone41251e2008-04-25 01:59:09 +0000277 .. method:: pack_into(buffer, offset, v1, v2, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Benjamin Petersone41251e2008-04-25 01:59:09 +0000279 Identical to the :func:`pack_into` function, using the compiled format.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000282 .. method:: unpack(bytes)
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Benjamin Petersone41251e2008-04-25 01:59:09 +0000284 Identical to the :func:`unpack` function, using the compiled format.
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000285 (``len(bytes)`` must equal :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
Georg Brandl7f01a132009-09-16 15:58:14 +0000288 .. method:: unpack_from(buffer, offset=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Benjamin Petersone41251e2008-04-25 01:59:09 +0000290 Identical to the :func:`unpack_from` function, using the compiled format.
291 (``len(buffer[offset:])`` must be at least :attr:`self.size`).
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
Benjamin Petersone41251e2008-04-25 01:59:09 +0000294 .. attribute:: format
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Benjamin Petersone41251e2008-04-25 01:59:09 +0000296 The format string used to construct this Struct object.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Benjamin Petersone41251e2008-04-25 01:59:09 +0000298 .. attribute:: size
Guido van Rossum04110fb2007-08-24 16:32:05 +0000299
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000300 The calculated size of the struct (and hence of the bytes) corresponding
Benjamin Petersone41251e2008-04-25 01:59:09 +0000301 to :attr:`format`.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000302