blob: fac10628c4437fd7b5ffbd612d49141002c0bd79 [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
Georg Brandl983d1002007-02-15 11:29:04 +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\end{funcdesc}
38
Fred Drakecce10901998-03-17 06:33:25 +000039\begin{funcdesc}{unpack}{fmt, string}
Fred Drake50b804d1998-11-30 22:14:58 +000040 Unpack the string (presumably packed by \code{pack(\var{fmt},
41 \textrm{\ldots})}) according to the given format. The result is a
42 tuple even if it contains exactly one item. The string must contain
Fred Drake907e76b2001-07-06 20:30:11 +000043 exactly the amount of data required by the format
44 (\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000045\end{funcdesc}
46
Georg Brandl983d1002007-02-15 11:29:04 +000047\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}}
48 Unpack the \var{buffer} according to tthe given format.
49 The result is a tuple even if it contains exactly one item. The
50 \var{buffer} must contain at least the amount of data required by the
51 format (\code{len(buffer[offset:])} must be at least
52 \code{calcsize(\var{fmt})}).
53\end{funcdesc}
54
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000055\begin{funcdesc}{calcsize}{fmt}
56 Return the size of the struct (and hence of the string)
57 corresponding to the given format.
58\end{funcdesc}
59
Fred Drake50b804d1998-11-30 22:14:58 +000060Format characters have the following meaning; the conversion between
Fred Drakeb68a1251999-08-24 20:16:29 +000061C and Python values should be obvious given their types:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000062
Fred Drake38e5d272000-04-03 20:13:55 +000063\begin{tableiv}{c|l|l|c}{samp}{Format}{C Type}{Python}{Notes}
64 \lineiv{x}{pad byte}{no value}{}
65 \lineiv{c}{\ctype{char}}{string of length 1}{}
66 \lineiv{b}{\ctype{signed char}}{integer}{}
67 \lineiv{B}{\ctype{unsigned char}}{integer}{}
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000068 \lineiv{t}{\ctype{_Bool}}{bool}{(1)}
Fred Drake38e5d272000-04-03 20:13:55 +000069 \lineiv{h}{\ctype{short}}{integer}{}
70 \lineiv{H}{\ctype{unsigned short}}{integer}{}
71 \lineiv{i}{\ctype{int}}{integer}{}
Tim Peters7b9542a2001-06-10 23:40:19 +000072 \lineiv{I}{\ctype{unsigned int}}{long}{}
Fred Drake38e5d272000-04-03 20:13:55 +000073 \lineiv{l}{\ctype{long}}{integer}{}
74 \lineiv{L}{\ctype{unsigned long}}{long}{}
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000075 \lineiv{q}{\ctype{long long}}{long}{(2)}
76 \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)}
Fred Drake38e5d272000-04-03 20:13:55 +000077 \lineiv{f}{\ctype{float}}{float}{}
78 \lineiv{d}{\ctype{double}}{float}{}
79 \lineiv{s}{\ctype{char[]}}{string}{}
80 \lineiv{p}{\ctype{char[]}}{string}{}
81 \lineiv{P}{\ctype{void *}}{integer}{}
82\end{tableiv}
83
84\noindent
85Notes:
86
87\begin{description}
88\item[(1)]
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000089 The \character{t} conversion code corresponds to the \ctype{_Bool} type
90 defined by C99. If this type is not available, it is simulated using a
91 \ctype{char}. In standard mode, it is always represented by one byte.
92 \versionadded{2.6}
93\item[(2)]
Tim Peters7b9542a2001-06-10 23:40:19 +000094 The \character{q} and \character{Q} conversion codes are available in
95 native mode only if the platform C compiler supports C \ctype{long long},
Fred Drake54d10fd2001-06-15 14:13:07 +000096 or, on Windows, \ctype{__int64}. They are always available in standard
Tim Peters7a3bfc32001-06-12 01:22:22 +000097 modes.
Fred Drake54d10fd2001-06-15 14:13:07 +000098 \versionadded{2.2}
Fred Drake38e5d272000-04-03 20:13:55 +000099\end{description}
100
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000101
Fred Drake907e76b2001-07-06 20:30:11 +0000102A format character may be preceded by an integral repeat count. For
103example, the format string \code{'4h'} means exactly the same as
Fred Drake50b804d1998-11-30 22:14:58 +0000104\code{'hhhh'}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000105
Guido van Rossume20aef51997-08-26 20:39:54 +0000106Whitespace characters between formats are ignored; a count and its
107format must not contain whitespace though.
108
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000109For the \character{s} format character, the count is interpreted as the
Guido van Rossum12543461996-12-31 02:22:14 +0000110size of the string, not a repeat count like for the other format
Fred Drake907e76b2001-07-06 20:30:11 +0000111characters; for example, \code{'10s'} means a single 10-byte string, while
Guido van Rossum12543461996-12-31 02:22:14 +0000112\code{'10c'} means 10 characters. For packing, the string is
113truncated or padded with null bytes as appropriate to make it fit.
114For unpacking, the resulting string always has exactly the specified
115number of bytes. As a special case, \code{'0s'} means a single, empty
116string (while \code{'0c'} means 0 characters).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000117
Tim Peters88091aa2001-09-15 18:09:22 +0000118The \character{p} format character encodes a "Pascal string", meaning
119a short variable-length string stored in a fixed number of bytes.
120The count is the total number of bytes stored. The first byte stored is
121the length of the string, or 255, whichever is smaller. The bytes
122of the string follow. If the string passed in to \function{pack()} is too
123long (longer than the count minus 1), only the leading count-1 bytes of the
Tim Peters5b7759f2001-09-15 18:16:27 +0000124string are stored. If the string is shorter than count-1, it is padded
Tim Peters88091aa2001-09-15 18:09:22 +0000125with null bytes so that exactly count bytes in all are used. Note that
126for \function{unpack()}, the \character{p} format character consumes count
127bytes, but that the string returned can never contain more than 255
128characters.
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000129
Tim Peters7a3bfc32001-06-12 01:22:22 +0000130For the \character{I}, \character{L}, \character{q} and \character{Q}
131format characters, the return value is a Python long integer.
Guido van Rossum12543461996-12-31 02:22:14 +0000132
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000133For the \character{P} format character, the return value is a Python
134integer or long integer, depending on the size needed to hold a
Fred Drake50b804d1998-11-30 22:14:58 +0000135pointer when it has been cast to an integer type. A \NULL{} pointer will
136always be returned as the Python integer \code{0}. When packing pointer-sized
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000137values, Python integer or long integer objects may be used. For
138example, the Alpha and Merced processors use 64-bit pointer values,
139meaning a Python long integer will be used to hold the pointer; other
140platforms use 32-bit pointers and will use a Python integer.
141
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000142For the \character{t} format character, the return value is either
143\constant{True} or \constant{False}. When packing, the truth value
144of the argument object is used. Either 0 or 1 in the native or standard
145bool representation will be packed, and any non-zero value will be True
146when unpacking.
147
Fred Drakeb68a1251999-08-24 20:16:29 +0000148By default, C numbers are represented in the machine's native format
Guido van Rossum12543461996-12-31 02:22:14 +0000149and byte order, and properly aligned by skipping pad bytes if
Fred Drakeb68a1251999-08-24 20:16:29 +0000150necessary (according to the rules used by the C compiler).
Guido van Rossum12543461996-12-31 02:22:14 +0000151
152Alternatively, the first character of the format string can be used to
153indicate the byte order, size and alignment of the packed data,
154according to the following table:
155
Fred Drakeee601911998-04-11 20:53:03 +0000156\begin{tableiii}{c|l|l}{samp}{Character}{Byte order}{Size and alignment}
Guido van Rossum12543461996-12-31 02:22:14 +0000157 \lineiii{@}{native}{native}
158 \lineiii{=}{native}{standard}
159 \lineiii{<}{little-endian}{standard}
160 \lineiii{>}{big-endian}{standard}
161 \lineiii{!}{network (= big-endian)}{standard}
162\end{tableiii}
163
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000164If the first character is not one of these, \character{@} is assumed.
Guido van Rossum12543461996-12-31 02:22:14 +0000165
166Native byte order is big-endian or little-endian, depending on the
Fred Drake907e76b2001-07-06 20:30:11 +0000167host system. For example, Motorola and Sun processors are big-endian;
168Intel and DEC processors are little-endian.
Guido van Rossum12543461996-12-31 02:22:14 +0000169
Fred Drakeb68a1251999-08-24 20:16:29 +0000170Native size and alignment are determined using the C compiler's
Fred Drake50b804d1998-11-30 22:14:58 +0000171\keyword{sizeof} expression. This is always combined with native byte
172order.
Guido van Rossum12543461996-12-31 02:22:14 +0000173
174Standard size and alignment are as follows: no alignment is required
Tim Peters7a3bfc32001-06-12 01:22:22 +0000175for any type (so you have to use pad bytes);
176\ctype{short} is 2 bytes;
177\ctype{int} and \ctype{long} are 4 bytes;
178\ctype{long long} (\ctype{__int64} on Windows) is 8 bytes;
179\ctype{float} and \ctype{double} are 32-bit and 64-bit
180IEEE floating point numbers, respectively.
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000181\ctype{_Bool} is 1 byte.
Guido van Rossum12543461996-12-31 02:22:14 +0000182
Fred Drake50b804d1998-11-30 22:14:58 +0000183Note the difference between \character{@} and \character{=}: both use
184native byte order, but the size and alignment of the latter is
185standardized.
Guido van Rossum12543461996-12-31 02:22:14 +0000186
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000187The form \character{!} is available for those poor souls who claim they
Guido van Rossum12543461996-12-31 02:22:14 +0000188can't remember whether network byte order is big-endian or
189little-endian.
190
Fred Drake907e76b2001-07-06 20:30:11 +0000191There is no way to indicate non-native byte order (force
Fred Drakecf0fb8b1998-07-23 21:18:25 +0000192byte-swapping); use the appropriate choice of \character{<} or
193\character{>}.
Guido van Rossum12543461996-12-31 02:22:14 +0000194
Guido van Rossum6ac06b31998-09-21 14:44:34 +0000195The \character{P} format character is only available for the native
196byte ordering (selected as the default or with the \character{@} byte
197order character). The byte order character \character{=} chooses to
198use little- or big-endian ordering based on the host system. The
199struct module does not interpret this as native ordering, so the
200\character{P} format is not available.
201
Guido van Rossum12543461996-12-31 02:22:14 +0000202Examples (all using native byte order, size and alignment, on a
203big-endian machine):
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000204
Fred Drake19479911998-02-13 06:58:54 +0000205\begin{verbatim}
Guido van Rossumdbadd551997-01-03 04:20:09 +0000206>>> from struct import *
207>>> pack('hhl', 1, 2, 3)
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000208'\x00\x01\x00\x02\x00\x00\x00\x03'
209>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
Guido van Rossumdbadd551997-01-03 04:20:09 +0000210(1, 2, 3)
211>>> calcsize('hhl')
2128
Fred Drake19479911998-02-13 06:58:54 +0000213\end{verbatim}
Fred Drake50b804d1998-11-30 22:14:58 +0000214
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215Hint: to align the end of a structure to the alignment requirement of
216a particular type, end the format with the code for that type with a
Fred Drake907e76b2001-07-06 20:30:11 +0000217repeat count of zero. For example, the format \code{'llh0l'}
218specifies two pad bytes at the end, assuming longs are aligned on
2194-byte boundaries. This only works when native size and alignment are
220in effect; standard size and alignment does not enforce any alignment.
Fred Drake7ddd0431998-03-08 07:44:13 +0000221
222\begin{seealso}
Fred Drakeb68a1251999-08-24 20:16:29 +0000223 \seemodule{array}{Packed binary storage of homogeneous data.}
224 \seemodule{xdrlib}{Packing and unpacking of XDR data.}
Fred Drake7ddd0431998-03-08 07:44:13 +0000225\end{seealso}
Georg Brandl983d1002007-02-15 11:29:04 +0000226
227\subsection{Struct Objects \label{struct-objects}}
228
229The \module{struct} module also defines the following type:
230
231\begin{classdesc}{Struct}{format}
232 Return a new Struct object which writes and reads binary data according to
233 the format string \var{format}. Creating a Struct object once and calling
234 its methods is more efficient than calling the \module{struct} functions
235 with the same format since the format string only needs to be compiled once.
236
237 \versionadded{2.5}
238\end{classdesc}
239
240Compiled Struct objects support the following methods and attributes:
241
242\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs}
243 Identical to the \function{pack()} function, using the compiled format.
244 (\code{len(result)} will equal \member{self.size}.)
245\end{methoddesc}
246
247\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs}
248 Identical to the \function{pack_into()} function, using the compiled format.
249\end{methoddesc}
250
251\begin{methoddesc}[Struct]{unpack}{string}
252 Identical to the \function{unpack()} function, using the compiled format.
253 (\code{len(string)} must equal \member{self.size}).
254\end{methoddesc}
255
256\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset
257 \code{= 0}}}
258 Identical to the \function{unpack_from()} function, using the compiled format.
259 (\code{len(buffer[offset:])} must be at least \member{self.size}).
260\end{methoddesc}
261
262\begin{memberdesc}[Struct]{format}
263 The format string used to construct this Struct object.
264\end{memberdesc}
265