rest25/library/struct.rst => rest262/library/struct.rst
f1
2:mod:`struct` --- Interpret strings as packed binary data
3=========================================================
4
5.. module:: struct
n6- 
n6+   :synopsis: Interpret strings as packed binary data.
7- 
8- 
9
10.. index::
11   pair: C; structures
12   triple: packing; binary; data
13
14This module performs conversions between Python values and C structs represented
15as Python strings.  It uses :dfn:`format strings` (explained below) as compact
16descriptions of the lay-out of the C structs and the intended conversion to/from
28
29.. function:: pack(fmt, v1, v2, ...)
30
31   Return a string containing the values ``v1, v2, ...`` packed according to the
32   given format.  The arguments must match the values required by the format
33   exactly.
34
35
n34+.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
35+ 
36+   Pack the values ``v1, v2, ...`` according to the given format, write the packed
37+   bytes into the writable *buffer* starting at *offset*. Note that the offset is
38+   a required argument.
39+ 
40+   .. versionadded:: 2.5
41+ 
42+ 
36.. function:: unpack(fmt, string)
37
38   Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the
39   given format.  The result is a tuple even if it contains exactly one item.  The
40   string must contain exactly the amount of data required by the format
41   (``len(string)`` must equal ``calcsize(fmt)``).
42
43
n51+.. function:: unpack_from(fmt, buffer[,offset=0])
52+ 
53+   Unpack the *buffer* according to tthe given format. The result is a tuple even
54+   if it contains exactly one item. The *buffer* must contain at least the amount
55+   of data required by the format (``len(buffer[offset:])`` must be at least
56+   ``calcsize(fmt)``).
57+ 
58+   .. versionadded:: 2.5
59+ 
60+ 
44.. function:: calcsize(fmt)
45
46   Return the size of the struct (and hence of the string) corresponding to the
47   given format.
48
49Format characters have the following meaning; the conversion between C and
50Python values should be obvious given their types:
51
55| ``x``  | pad byte                | no value           |       |
56+--------+-------------------------+--------------------+-------+
57| ``c``  | :ctype:`char`           | string of length 1 |       |
58+--------+-------------------------+--------------------+-------+
59| ``b``  | :ctype:`signed char`    | integer            |       |
60+--------+-------------------------+--------------------+-------+
61| ``B``  | :ctype:`unsigned char`  | integer            |       |
62+--------+-------------------------+--------------------+-------+
n80+| ``?``  | :ctype:`_Bool`          | bool               | \(1)  |
81++--------+-------------------------+--------------------+-------+
63| ``h``  | :ctype:`short`          | integer            |       |
64+--------+-------------------------+--------------------+-------+
65| ``H``  | :ctype:`unsigned short` | integer            |       |
66+--------+-------------------------+--------------------+-------+
67| ``i``  | :ctype:`int`            | integer            |       |
68+--------+-------------------------+--------------------+-------+
n69-| ``I``  | :ctype:`unsigned int`   | long               |       |
n88+| ``I``  | :ctype:`unsigned int`   | integer or long    |       |
70+--------+-------------------------+--------------------+-------+
71| ``l``  | :ctype:`long`           | integer            |       |
72+--------+-------------------------+--------------------+-------+
73| ``L``  | :ctype:`unsigned long`  | long               |       |
74+--------+-------------------------+--------------------+-------+
n75-| ``q``  | :ctype:`long long`      | long               | \(1)  |
n94+| ``q``  | :ctype:`long long`      | long               | \(2)  |
76+--------+-------------------------+--------------------+-------+
n77-| ``Q``  | :ctype:`unsigned long   | long               | \(1)  |
n96+| ``Q``  | :ctype:`unsigned long   | long               | \(2)  |
78|        | long`                   |                    |       |
79+--------+-------------------------+--------------------+-------+
80| ``f``  | :ctype:`float`          | float              |       |
81+--------+-------------------------+--------------------+-------+
82| ``d``  | :ctype:`double`         | float              |       |
83+--------+-------------------------+--------------------+-------+
84| ``s``  | :ctype:`char[]`         | string             |       |
85+--------+-------------------------+--------------------+-------+
86| ``p``  | :ctype:`char[]`         | string             |       |
87+--------+-------------------------+--------------------+-------+
n88-| ``P``  | :ctype:`void \*`        | integer            |       |
n107+| ``P``  | :ctype:`void \*`        | long               |       |
89+--------+-------------------------+--------------------+-------+
90
91Notes:
92
93(1)
n113+   The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by
114+   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+ 
117+   .. versionadded:: 2.6
118+ 
119+(2)
94   The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
95   the platform C compiler supports C :ctype:`long long`, or, on Windows,
96   :ctype:`__int64`.  They are always available in standard modes.
97
98   .. versionadded:: 2.2
99
100A format character may be preceded by an integral repeat count.  For example,
101the format string ``'4h'`` means exactly the same as ``'hhhh'``.
127For the ``'P'`` format character, the return value is a Python integer or long
128integer, depending on the size needed to hold a pointer when it has been cast to
129an integer type.  A *NULL* pointer will always be returned as the Python integer
130``0``. When packing pointer-sized values, Python integer or long integer objects
131may be used.  For example, the Alpha and Merced processors use 64-bit pointer
132values, meaning a Python long integer will be used to hold the pointer; other
133platforms use 32-bit pointers and will use a Python integer.
134
n161+For the ``'?'`` format character, the return value is either :const:`True` or
162+:const:`False`. When packing, the truth value of the argument object is used.
163+Either 0 or 1 in the native or standard bool representation will be packed, and
164+any non-zero value will be True when unpacking.
165+ 
135By default, C numbers are represented in the machine's native format and byte
136order, and properly aligned by skipping pad bytes if necessary (according to the
137rules used by the C compiler).
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
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 host system.
160For example, Motorola and Sun processors are big-endian; Intel and DEC
161processors are little-endian.
162
163Native size and alignment are determined using the C compiler's
n164-:keyword:`sizeof` expression.  This is always combined with native byte order.
n195+``sizeof`` expression.  This is always combined with native byte order.
165
166Standard size and alignment are as follows: no alignment is required for any
167type (so you have to use pad bytes); :ctype:`short` is 2 bytes; :ctype:`int` and
168:ctype:`long` are 4 bytes; :ctype:`long long` (:ctype:`__int64` on Windows) is 8
169bytes; :ctype:`float` and :ctype:`double` are 32-bit and 64-bit IEEE floating
n170-point numbers, respectively.
n201+point numbers, respectively. :ctype:`_Bool` is 1 byte.
171
172Note the difference between ``'@'`` and ``'='``: both use native byte order, but
173the size and alignment of the latter is standardized.
174
175The form ``'!'`` is available for those poor souls who claim they can't remember
176whether network byte order is big-endian or little-endian.
177
178There is no way to indicate non-native byte order (force byte-swapping); use the
197
198Hint: to align the end of a structure to the alignment requirement of a
199particular type, end the format with the code for that type with a repeat count
200of zero.  For example, the format ``'llh0l'`` specifies two pad bytes at the
201end, assuming longs are aligned on 4-byte boundaries.  This only works when
202native size and alignment are in effect; standard size and alignment does not
203enforce any alignment.
204
n236+Unpacked fields can be named by assigning them to variables or by wrapping
237+the result in a named tuple::
238+ 
239+    >>> record = 'raymond   \x32\x12\x08\x01\x08'
240+    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
241+ 
242+    >>> from collections import namedtuple
243+    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
244+    >>> Student._make(unpack('<10sHHb', s))
245+    Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)
205
206.. seealso::
207
208   Module :mod:`array`
209      Packed binary storage of homogeneous data.
210
211   Module :mod:`xdrlib`
212      Packing and unpacking of XDR data.
213
t255+ 
256+.. _struct-objects:
257+ 
258+Struct Objects
259+--------------
260+ 
261+The :mod:`struct` module also defines the following type:
262+ 
263+ 
264+.. class:: Struct(format)
265+ 
266+   Return a new Struct object which writes and reads binary data according to the
267+   format string *format*.  Creating a Struct object once and calling its methods
268+   is more efficient than calling the :mod:`struct` functions with the same format
269+   since the format string only needs to be compiled once.
270+ 
271+   .. versionadded:: 2.5
272+ 
273+   Compiled Struct objects support the following methods and attributes:
274+ 
275+ 
276+   .. method:: pack(v1, v2, ...)
277+ 
278+      Identical to the :func:`pack` function, using the compiled format.
279+      (``len(result)`` will equal :attr:`self.size`.)
280+ 
281+ 
282+   .. method:: pack_into(buffer, offset, v1, v2, ...)
283+ 
284+      Identical to the :func:`pack_into` function, using the compiled format.
285+ 
286+ 
287+   .. method:: unpack(string)
288+ 
289+      Identical to the :func:`unpack` function, using the compiled format.
290+      (``len(string)`` must equal :attr:`self.size`).
291+ 
292+ 
293+   .. method:: unpack_from(buffer[, offset=0])
294+ 
295+      Identical to the :func:`unpack_from` function, using the compiled format.
296+      (``len(buffer[offset:])`` must be at least :attr:`self.size`).
297+ 
298+ 
299+   .. attribute:: format
300+ 
301+      The format string used to construct this Struct object.
302+ 
303+   .. attribute:: size
304+ 
305+      The calculated size of the struct (and hence of the string) corresponding
306+      to :attr:`format`.
307+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op