blob: 68c5c9adc6995b9530068c45cd31c55ad1ca9959 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{struct} ---
Fred Drakeb68a1251999-08-24 20:16:29 +00002 Interpret strings as packed binary data}
Fred Drakeb91e9341998-07-23 17:59:49 +00003\declaremodule{builtin}{struct}
4
5\modulesynopsis{Interpret strings as packed binary data.}
6
Fred Drakeb68a1251999-08-24 20:16:29 +00007\indexii{C}{structures}
8\indexiii{packing}{binary}{data}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00009
Fred Drakeb68a1251999-08-24 20:16:29 +000010This module performs conversions between Python values and C
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000011structs represented as Python strings. It uses \dfn{format strings}
Fred Drakeb68a1251999-08-24 20:16:29 +000012(explained below) as compact descriptions of the lay-out of the C
13structs and the intended conversion to/from Python values. This can
14be used in handling binary data stored in files or from network
15connections, among other sources.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000016
17The module defines the following exception and functions:
18
Fred Drake7ddd0431998-03-08 07:44:13 +000019
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000020\begin{excdesc}{error}
21 Exception raised on various occasions; argument is a string
22 describing what is wrong.
23\end{excdesc}
24
Fred Drake50b804d1998-11-30 22:14:58 +000025\begin{funcdesc}{pack}{fmt, v1, v2, \textrm{\ldots}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000026 Return a string containing the values
Fred Drake50b804d1998-11-30 22:14:58 +000027 \code{\var{v1}, \var{v2}, \textrm{\ldots}} packed according to the given
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000028 format. The arguments must match the values required by the format
29 exactly.
30\end{funcdesc}
31
Thomas Wouterscf297e42007-02-23 15:07:44 +000032\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs}
33 Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given
34 format, write the packed bytes into the writable \var{buffer} starting at
35 \var{offset}.
36 Note that the offset is not an optional argument.
37
38 \versionadded{2.5}
39\end{funcdesc}
40
Fred Drakecce10901998-03-17 06:33:25 +000041\begin{funcdesc}{unpack}{fmt, string}
Fred Drake50b804d1998-11-30 22:14:58 +000042 Unpack the string (presumably packed by \code{pack(\var{fmt},
43 \textrm{\ldots})}) according to the given format. The result is a
44 tuple even if it contains exactly one item. The string must contain
Fred Drake907e76b2001-07-06 20:30:11 +000045 exactly the amount of data required by the format
46 (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000047\end{funcdesc}
48
Thomas Wouterscf297e42007-02-23 15:07:44 +000049\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}}
50 Unpack the \var{buffer} according to tthe given format.
51 The result is a tuple even if it contains exactly one item. The
52 \var{buffer} must contain at least the amount of data required by the
53 format (\code{len(buffer[offset:])} must be at least
54 \code{calcsize(\var{fmt})}).
55
56 \versionadded{2.5}
57\end{funcdesc}
58
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000059\begin{funcdesc}{calcsize}{fmt}
60 Return the size of the struct (and hence of the string)
61 corresponding to the given format.
62\end{funcdesc}
63
Fred Drake50b804d1998-11-30 22:14:58 +000064Format characters have the following meaning; the conversion between
Fred Drakeb68a1251999-08-24 20:16:29 +000065C and Python values should be obvious given their types:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000066
Fred Drake38e5d272000-04-03 20:13:55 +000067\begin{tableiv}{c|l|l|c}{samp}{Format}{C Type}{Python}{Notes}
68 \lineiv{x}{pad byte}{no value}{}
69 \lineiv{c}{\ctype{char}}{string of length 1}{}
70 \lineiv{b}{\ctype{signed char}}{integer}{}
71 \lineiv{B}{\ctype{unsigned char}}{integer}{}
Thomas Woutersb2137042007-02-01 18:02:27 +000072 \lineiv{t}{\ctype{_Bool}}{bool}{(1)}
Fred Drake38e5d272000-04-03 20:13:55 +000073 \lineiv{h}{\ctype{short}}{integer}{}
74 \lineiv{H}{\ctype{unsigned short}}{integer}{}
75 \lineiv{i}{\ctype{int}}{integer}{}
Tim Peters7b9542a2001-06-10 23:40:19 +000076 \lineiv{I}{\ctype{unsigned int}}{long}{}
Fred Drake38e5d272000-04-03 20:13:55 +000077 \lineiv{l}{\ctype{long}}{integer}{}
78 \lineiv{L}{\ctype{unsigned long}}{long}{}
Thomas Woutersb2137042007-02-01 18:02:27 +000079 \lineiv{q}{\ctype{long long}}{long}{(2)}
80 \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)}
Fred Drake38e5d272000-04-03 20:13:55 +000081 \lineiv{f}{\ctype{float}}{float}{}
82 \lineiv{d}{\ctype{double}}{float}{}
83 \lineiv{s}{\ctype{char[]}}{string}{}
84 \lineiv{p}{\ctype{char[]}}{string}{}
85 \lineiv{P}{\ctype{void *}}{integer}{}
86\end{tableiv}
87
88\noindent
89Notes:
90
91\begin{description}
92\item[(1)]
Thomas Woutersb2137042007-02-01 18:02:27 +000093 The \character{t} conversion code corresponds to the \ctype{_Bool} type
94 defined by C99. If this type is not available, it is simulated using a
95 \ctype{char}. In standard mode, it is always represented by one byte.
96 \versionadded{2.6}
97\item[(2)]
Tim Peters7b9542a2001-06-10 23:40:19 +000098 The \character{q} and \character{Q} conversion codes are available in
99 native mode only if the platform C compiler supports C \ctype{long long},
Fred Drake54d10fd2001-06-15 14:13:07 +0000100 or, on Windows, \ctype{__int64}. They are always available in standard
Tim Peters7a3bfc32001-06-12 01:22:22 +0000101 modes.
Fred Drake54d10fd2001-06-15 14:13:07 +0000102 \versionadded{2.2}
Fred Drake38e5d272000-04-03 20:13:55 +0000103\end{description}
104
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000105
Fred Drake907e76b2001-07-06 20:30:11 +0000106A format character may be preceded by an integral repeat count. For
107example, the format string \code{'4h'} means exactly the same as
Fred Drake50b804d1998-11-30 22:14:58 +0000108\code{'hhhh'}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000109
Guido van Rossume20aef51997-08-26 20:39:54 +0000110Whitespace characters between formats are ignored; a count and its
111format must not contain whitespace though.
112
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000113For the \character{s} format character, the count is interpreted as the
Guido van Rossum12543461996-12-31 02:22:14 +0000114size of the string, not a repeat count like for the other format
Fred Drake907e76b2001-07-06 20:30:11 +0000115characters; for example, \code{'10s'} means a single 10-byte string, while
Guido van Rossum12543461996-12-31 02:22:14 +0000116\code{'10c'} means 10 characters. For packing, the string is
117truncated or padded with null bytes as appropriate to make it fit.
118For unpacking, the resulting string always has exactly the specified
119number of bytes. As a special case, \code{'0s'} means a single, empty
120string (while \code{'0c'} means 0 characters).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000121
Tim Peters88091aa2001-09-15 18:09:22 +0000122The \character{p} format character encodes a "Pascal string", meaning
123a short variable-length string stored in a fixed number of bytes.
124The count is the total number of bytes stored. The first byte stored is
125the length of the string, or 255, whichever is smaller. The bytes
126of the string follow. If the string passed in to \function{pack()} is too
127long (longer than the count minus 1), only the leading count-1 bytes of the
Tim Peters5b7759f2001-09-15 18:16:27 +0000128string are stored. If the string is shorter than count-1, it is padded
Tim Peters88091aa2001-09-15 18:09:22 +0000129with null bytes so that exactly count bytes in all are used. Note that
130for \function{unpack()}, the \character{p} format character consumes count
131bytes, but that the string returned can never contain more than 255
132characters.
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000133
Tim Peters7a3bfc32001-06-12 01:22:22 +0000134For the \character{I}, \character{L}, \character{q} and \character{Q}
135format characters, the return value is a Python long integer.
Guido van Rossum12543461996-12-31 02:22:14 +0000136
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000137For the \character{P} format character, the return value is a Python
138integer or long integer, depending on the size needed to hold a
Fred Drake50b804d1998-11-30 22:14:58 +0000139pointer when it has been cast to an integer type. A \NULL{} pointer will
140always be returned as the Python integer \code{0}. When packing pointer-sized
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000141values, Python integer or long integer objects may be used. For
142example, the Alpha and Merced processors use 64-bit pointer values,
143meaning a Python long integer will be used to hold the pointer; other
144platforms use 32-bit pointers and will use a Python integer.
145
Thomas Woutersb2137042007-02-01 18:02:27 +0000146For the \character{t} format character, the return value is either
147\constant{True} or \constant{False}. When packing, the truth value
148of the argument object is used. Either 0 or 1 in the native or standard
149bool representation will be packed, and any non-zero value will be True
150when unpacking.
151
Fred Drakeb68a1251999-08-24 20:16:29 +0000152By default, C numbers are represented in the machine's native format
Guido van Rossum12543461996-12-31 02:22:14 +0000153and byte order, and properly aligned by skipping pad bytes if
Fred Drakeb68a1251999-08-24 20:16:29 +0000154necessary (according to the rules used by the C compiler).
Guido van Rossum12543461996-12-31 02:22:14 +0000155
156Alternatively, the first character of the format string can be used to
157indicate the byte order, size and alignment of the packed data,
158according to the following table:
159
Fred Drakeee601911998-04-11 20:53:03 +0000160\begin{tableiii}{c|l|l}{samp}{Character}{Byte order}{Size and alignment}
Guido van Rossum12543461996-12-31 02:22:14 +0000161 \lineiii{@}{native}{native}
162 \lineiii{=}{native}{standard}
163 \lineiii{<}{little-endian}{standard}
164 \lineiii{>}{big-endian}{standard}
165 \lineiii{!}{network (= big-endian)}{standard}
166\end{tableiii}
167
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000168If the first character is not one of these, \character{@} is assumed.
Guido van Rossum12543461996-12-31 02:22:14 +0000169
170Native byte order is big-endian or little-endian, depending on the
Fred Drake907e76b2001-07-06 20:30:11 +0000171host system. For example, Motorola and Sun processors are big-endian;
172Intel and DEC processors are little-endian.
Guido van Rossum12543461996-12-31 02:22:14 +0000173
Fred Drakeb68a1251999-08-24 20:16:29 +0000174Native size and alignment are determined using the C compiler's
Fred Drake50b804d1998-11-30 22:14:58 +0000175\keyword{sizeof} expression. This is always combined with native byte
176order.
Guido van Rossum12543461996-12-31 02:22:14 +0000177
178Standard size and alignment are as follows: no alignment is required
Tim Peters7a3bfc32001-06-12 01:22:22 +0000179for any type (so you have to use pad bytes);
180\ctype{short} is 2 bytes;
181\ctype{int} and \ctype{long} are 4 bytes;
182\ctype{long long} (\ctype{__int64} on Windows) is 8 bytes;
183\ctype{float} and \ctype{double} are 32-bit and 64-bit
184IEEE floating point numbers, respectively.
Thomas Woutersb2137042007-02-01 18:02:27 +0000185\ctype{_Bool} is 1 byte.
Guido van Rossum12543461996-12-31 02:22:14 +0000186
Fred Drake50b804d1998-11-30 22:14:58 +0000187Note the difference between \character{@} and \character{=}: both use
188native byte order, but the size and alignment of the latter is
189standardized.
Guido van Rossum12543461996-12-31 02:22:14 +0000190
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000191The form \character{!} is available for those poor souls who claim they
Guido van Rossum12543461996-12-31 02:22:14 +0000192can't remember whether network byte order is big-endian or
193little-endian.
194
Fred Drake907e76b2001-07-06 20:30:11 +0000195There is no way to indicate non-native byte order (force
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000196byte-swapping); use the appropriate choice of \character{<} or
197\character{>}.
Guido van Rossum12543461996-12-31 02:22:14 +0000198
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000199The \character{P} format character is only available for the native
200byte ordering (selected as the default or with the \character{@} byte
201order character). The byte order character \character{=} chooses to
202use little- or big-endian ordering based on the host system. The
203struct module does not interpret this as native ordering, so the
204\character{P} format is not available.
205
Guido van Rossum12543461996-12-31 02:22:14 +0000206Examples (all using native byte order, size and alignment, on a
207big-endian machine):
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000208
Fred Drake19479911998-02-13 06:58:54 +0000209\begin{verbatim}
Guido van Rossumdbadd551997-01-03 04:20:09 +0000210>>> from struct import *
211>>> pack('hhl', 1, 2, 3)
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000212'\x00\x01\x00\x02\x00\x00\x00\x03'
213>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
Guido van Rossumdbadd551997-01-03 04:20:09 +0000214(1, 2, 3)
215>>> calcsize('hhl')
2168
Fred Drake19479911998-02-13 06:58:54 +0000217\end{verbatim}
Fred Drake50b804d1998-11-30 22:14:58 +0000218
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000219Hint: to align the end of a structure to the alignment requirement of
220a particular type, end the format with the code for that type with a
Fred Drake907e76b2001-07-06 20:30:11 +0000221repeat count of zero. For example, the format \code{'llh0l'}
222specifies two pad bytes at the end, assuming longs are aligned on
2234-byte boundaries. This only works when native size and alignment are
224in effect; standard size and alignment does not enforce any alignment.
Fred Drake7ddd0431998-03-08 07:44:13 +0000225
226\begin{seealso}
Fred Drakeb68a1251999-08-24 20:16:29 +0000227 \seemodule{array}{Packed binary storage of homogeneous data.}
228 \seemodule{xdrlib}{Packing and unpacking of XDR data.}
Fred Drake7ddd0431998-03-08 07:44:13 +0000229\end{seealso}
Thomas Wouterscf297e42007-02-23 15:07:44 +0000230
231\subsection{Struct Objects \label{struct-objects}}
232
233The \module{struct} module also defines the following type:
234
235\begin{classdesc}{Struct}{format}
236 Return a new Struct object which writes and reads binary data according to
237 the format string \var{format}. Creating a Struct object once and calling
238 its methods is more efficient than calling the \module{struct} functions
239 with the same format since the format string only needs to be compiled once.
240
241 \versionadded{2.5}
242\end{classdesc}
243
244Compiled Struct objects support the following methods and attributes:
245
246\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs}
247 Identical to the \function{pack()} function, using the compiled format.
248 (\code{len(result)} will equal \member{self.size}.)
249\end{methoddesc}
250
251\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs}
252 Identical to the \function{pack_into()} function, using the compiled format.
253\end{methoddesc}
254
255\begin{methoddesc}[Struct]{unpack}{string}
256 Identical to the \function{unpack()} function, using the compiled format.
257 (\code{len(string)} must equal \member{self.size}).
258\end{methoddesc}
259
260\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset
261 \code{= 0}}}
262 Identical to the \function{unpack_from()} function, using the compiled format.
263 (\code{len(buffer[offset:])} must be at least \member{self.size}).
264\end{methoddesc}
265
266\begin{memberdesc}[Struct]{format}
267 The format string used to construct this Struct object.
268\end{memberdesc}
269