parthtamu/rag-code-assistant
0
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="struct — Interpret bytes as packed binary data" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/struct.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/struct.py This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python valu..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_struct_eb4ddbd9.png" />15<meta property="og:image:alt" content="Source code: Lib/struct.py This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python valu..." />16<meta name="description" content="Source code: Lib/struct.py This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python valu..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20 <title>struct — Interpret bytes as packed binary data — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21 22 <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23 <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24 <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25 <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26 <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27 28 <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29 <script src="../_static/doctools.js?v=9bcbadda"></script>30 <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31 <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32 33 <script src="../_static/sidebar.js"></script>34 35 <link rel="search" type="application/opensearchdescription+xml"36 title="Search within Python 3.15.0a6 documentation"37 href="../_static/opensearch.xml"/>38 <link rel="author" title="About these documents" href="../about.html" />39 <link rel="index" title="Index" href="../genindex.html" />40 <link rel="search" title="Search" href="../search.html" />41 <link rel="copyright" title="Copyright" href="../copyright.html" />42 <link rel="next" title="codecs — Codec registry and base classes" href="codecs.html" />43 <link rel="prev" title="Binary Data Services" href="binary.html" />44 45 46 <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47 48 <link rel="canonical" href="https://docs.python.org/3/library/struct.html">49 50 51 52 53 <style>54 @media only screen {55 table.full-width-table {56 width: 100%;57 }58 }59 </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61 <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62 <script type="text/javascript" src="../_static/copybutton.js"></script>63 <script type="text/javascript" src="../_static/menu.js"></script>64 <script type="text/javascript" src="../_static/search-focus.js"></script>65 <script type="text/javascript" src="../_static/themetoggle.js"></script> 66 <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67 <meta name="readthedocs-addons-api-version" content="1">68 69 </head>70<body>71<div class="mobile-nav">72 <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73 aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74 <nav class="nav-content" role="navigation">75 <label for="menuToggler" class="toggler__label">76 <span></span>77 </label>78 <span class="nav-items-wrapper">79 <a href="https://www.python.org/" class="nav-logo">80 <img src="../_static/py.svg" alt="Python logo">81 </a>82 <span class="version_switcher_placeholder"></span>83 <form role="search" class="search" action="../search.html" method="get">84 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85 <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86 </svg>87 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88 <input type="submit" value="Go">89 </form>90 </span>91 </nav>92 <div class="menu-wrapper">93 <nav class="menu" role="navigation" aria-label="main navigation">94 <div class="language_switcher_placeholder"></div>95 96<label class="theme-selector-label">97 Theme98 <select class="theme-selector" oninput="activateTheme(this.value)">99 <option value="auto" selected>Auto</option>100 <option value="light">Light</option>101 <option value="dark">Dark</option>102 </select>103</label>104 <div>105 <h3><a href="../contents.html">Table of Contents</a></h3>106 <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> — Interpret bytes as packed binary data</a><ul>108<li><a class="reference internal" href="#functions-and-exceptions">Functions and Exceptions</a></li>109<li><a class="reference internal" href="#format-strings">Format Strings</a><ul>110<li><a class="reference internal" href="#byte-order-size-and-alignment">Byte Order, Size, and Alignment</a></li>111<li><a class="reference internal" href="#format-characters">Format Characters</a></li>112<li><a class="reference internal" href="#examples">Examples</a></li>113</ul>114</li>115<li><a class="reference internal" href="#applications">Applications</a><ul>116<li><a class="reference internal" href="#native-formats">Native Formats</a></li>117<li><a class="reference internal" href="#standard-formats">Standard Formats</a></li>118</ul>119</li>120<li><a class="reference internal" href="#classes">Classes</a></li>121</ul>122</li>123</ul>124 125 </div>126 <div>127 <h4>Previous topic</h4>128 <p class="topless"><a href="binary.html"129 title="previous chapter">Binary Data Services</a></p>130 </div>131 <div>132 <h4>Next topic</h4>133 <p class="topless"><a href="codecs.html"134 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a></p>135 </div>136 <script>137 document.addEventListener('DOMContentLoaded', () => {138 const title = document.querySelector('meta[property="og:title"]').content;139 const elements = document.querySelectorAll('.improvepage');140 const pageurl = window.location.href.split('?')[0];141 elements.forEach(element => {142 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));143 url.searchParams.set('pagetitle', title);144 url.searchParams.set('pageurl', pageurl);145 url.searchParams.set('pagesource', "library/struct.rst");146 element.href = url.toString();147 });148 });149 </script>150 <div role="note" aria-label="source link">151 <h3>This page</h3>152 <ul class="this-page-menu">153 <li><a href="../bugs.html">Report a bug</a></li>154 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>155 <li>156 <a href="https://github.com/python/cpython/blob/main/Doc/library/struct.rst?plain=1"157 rel="nofollow">Show source158 </a>159 </li>160 161 </ul>162 </div>163 </nav>164 </div>165</div>166 167 168 <div class="related" role="navigation" aria-label="Related">169 <h3>Navigation</h3>170 <ul>171 <li class="right" style="margin-right: 10px">172 <a href="../genindex.html" title="General Index"173 accesskey="I">index</a></li>174 <li class="right" >175 <a href="../py-modindex.html" title="Python Module Index"176 >modules</a> |</li>177 <li class="right" >178 <a href="codecs.html" title="codecs — Codec registry and base classes"179 accesskey="N">next</a> |</li>180 <li class="right" >181 <a href="binary.html" title="Binary Data Services"182 accesskey="P">previous</a> |</li>183 184 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>185 <li><a href="https://www.python.org/">Python</a> »</li>186 <li class="switchers">187 <div class="language_switcher_placeholder"></div>188 <div class="version_switcher_placeholder"></div>189 </li>190 <li>191 192 </li>193 <li id="cpython-language-and-version">194 <a href="../index.html">3.15.0a6 Documentation</a> »195 </li>196 197 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>198 <li class="nav-item nav-item-2"><a href="binary.html" accesskey="U">Binary Data Services</a> »</li>199 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> — Interpret bytes as packed binary data</a></li>200 <li class="right">201 202 203 <div class="inline-search" role="search">204 <form class="inline-search" action="../search.html" method="get">205 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">206 <input type="submit" value="Go">207 </form>208 </div>209 |210 </li>211 <li class="right">212<label class="theme-selector-label">213 Theme214 <select class="theme-selector" oninput="activateTheme(this.value)">215 <option value="auto" selected>Auto</option>216 <option value="light">Light</option>217 <option value="dark">Dark</option>218 </select>219</label> |</li>220 221 </ul>222 </div> 223 224 <div class="document">225 <div class="documentwrapper">226 <div class="bodywrapper">227 <div class="body" role="main">228 229 <section id="struct-interpret-bytes-as-packed-binary-data">230<h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> — Interpret bytes as packed binary data<a class="headerlink" href="#struct-interpret-bytes-as-packed-binary-data" title="Link to this heading">¶</a></h1>231<p id="module-struct"><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/struct.py">Lib/struct.py</a></p>232<hr class="docutils" id="index-0" />233<p>This module converts between Python values and C structs represented234as Python <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects. Compact <a class="reference internal" href="#struct-format-strings"><span class="std std-ref">format strings</span></a>235describe the intended conversions to/from Python values.236The module’s functions and objects can be used for two largely237distinct applications, data exchange with external sources (files or238network connections), or data transfer between the Python application239and the C layer.</p>240<div class="admonition note">241<p class="admonition-title">Note</p>242<p>When no prefix character is given, native mode is the default. It243packs or unpacks data based on the platform and compiler on which244the Python interpreter was built.245The result of packing a given C struct includes pad bytes which246maintain proper alignment for the C types involved; similarly,247alignment is taken into account when unpacking. In contrast, when248communicating data between external sources, the programmer is249responsible for defining byte ordering and padding between elements.250See <a class="reference internal" href="#struct-alignment"><span class="std std-ref">Byte Order, Size, and Alignment</span></a> for details.</p>251</div>252<p>Several <code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> functions (and methods of <a class="reference internal" href="#struct.Struct" title="struct.Struct"><code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code></a>) take a <em>buffer</em>253argument. This refers to objects that implement the <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">Buffer Protocol</span></a> and254provide either a readable or read-writable buffer. The most common types used255for that purpose are <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> and <a class="reference internal" href="stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, but many other types256that can be viewed as an array of bytes implement the buffer protocol, so that257they can be read/filled without additional copying from a <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> object.</p>258<section id="functions-and-exceptions">259<h2>Functions and Exceptions<a class="headerlink" href="#functions-and-exceptions" title="Link to this heading">¶</a></h2>260<p>The module defines the following exception and functions:</p>261<dl class="py exception">262<dt class="sig sig-object py" id="struct.error">263<em class="property"><span class="k"><span class="pre">exception</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">error</span></span><a class="headerlink" href="#struct.error" title="Link to this definition">¶</a></dt>264<dd><p>Exception raised on various occasions; argument is a string describing what265is wrong.</p>266</dd></dl>267 268<dl class="py function">269<dt class="sig sig-object py" id="struct.pack">270<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">pack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v2</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.pack" title="Link to this definition">¶</a></dt>271<dd><p>Return a bytes object containing the values <em>v1</em>, <em>v2</em>, … packed according272to the format string <em>format</em>. The arguments must match the values required by273the format exactly.</p>274</dd></dl>275 276<dl class="py function">277<dt class="sig sig-object py" id="struct.pack_into">278<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">pack_into</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">offset</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v2</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.pack_into" title="Link to this definition">¶</a></dt>279<dd><p>Pack the values <em>v1</em>, <em>v2</em>, … according to the format string <em>format</em> and280write the packed bytes into the writable buffer <em>buffer</em> starting at281position <em>offset</em>. Note that <em>offset</em> is a required argument.</p>282</dd></dl>283 284<dl class="py function">285<dt class="sig sig-object py" id="struct.unpack">286<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">unpack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.unpack" title="Link to this definition">¶</a></dt>287<dd><p>Unpack from the buffer <em>buffer</em> (presumably packed by <code class="docutils literal notranslate"><span class="pre">pack(format,</span> <span class="pre">...)</span></code>)288according to the format string <em>format</em>. The result is a tuple even if it289contains exactly one item. The buffer’s size in bytes must match the290size required by the format, as reflected by <a class="reference internal" href="#struct.calcsize" title="struct.calcsize"><code class="xref py py-func docutils literal notranslate"><span class="pre">calcsize()</span></code></a>.</p>291</dd></dl>292 293<dl class="py function">294<dt class="sig sig-object py" id="struct.unpack_from">295<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">unpack_from</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em>, <em class="sig-param"><span class="positional-only-separator o"><abbr title="Positional-only parameter separator (PEP 570)"><span class="pre">/</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">offset</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.unpack_from" title="Link to this definition">¶</a></dt>296<dd><p>Unpack from <em>buffer</em> starting at position <em>offset</em>, according to the format297string <em>format</em>. The result is a tuple even if it contains exactly one298item. The buffer’s size in bytes, starting at position <em>offset</em>, must be at299least the size required by the format, as reflected by <a class="reference internal" href="#struct.calcsize" title="struct.calcsize"><code class="xref py py-func docutils literal notranslate"><span class="pre">calcsize()</span></code></a>.</p>300</dd></dl>301 302<dl class="py function">303<dt class="sig sig-object py" id="struct.iter_unpack">304<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">iter_unpack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.iter_unpack" title="Link to this definition">¶</a></dt>305<dd><p>Iteratively unpack from the buffer <em>buffer</em> according to the format306string <em>format</em>. This function returns an iterator which will read307equally sized chunks from the buffer until all its contents have been308consumed. The buffer’s size in bytes must be a multiple of the size309required by the format, as reflected by <a class="reference internal" href="#struct.calcsize" title="struct.calcsize"><code class="xref py py-func docutils literal notranslate"><span class="pre">calcsize()</span></code></a>.</p>310<p>Each iteration yields a tuple as specified by the format string.</p>311<div class="versionadded">312<p><span class="versionmodified added">Added in version 3.4.</span></p>313</div>314</dd></dl>315 316<dl class="py function">317<dt class="sig sig-object py" id="struct.calcsize">318<span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">calcsize</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.calcsize" title="Link to this definition">¶</a></dt>319<dd><p>Return the size of the struct (and hence of the bytes object produced by320<code class="docutils literal notranslate"><span class="pre">pack(format,</span> <span class="pre">...)</span></code>) corresponding to the format string <em>format</em>.</p>321</dd></dl>322 323</section>324<section id="format-strings">325<span id="struct-format-strings"></span><h2>Format Strings<a class="headerlink" href="#format-strings" title="Link to this heading">¶</a></h2>326<p>Format strings describe the data layout when327packing and unpacking data. They are built up from <a class="reference internal" href="#format-characters"><span class="std std-ref">format characters</span></a>,328which specify the type of data being packed/unpacked. In addition,329special characters control the <a class="reference internal" href="#struct-alignment"><span class="std std-ref">byte order, size and alignment</span></a>.330Each format string consists of an optional prefix character which331describes the overall properties of the data and one or more format332characters which describe the actual data values and padding.</p>333<section id="byte-order-size-and-alignment">334<span id="struct-alignment"></span><h3>Byte Order, Size, and Alignment<a class="headerlink" href="#byte-order-size-and-alignment" title="Link to this heading">¶</a></h3>335<p>By default, C types are represented in the machine’s native format and byte336order, and properly aligned by skipping pad bytes if necessary (according to the337rules used by the C compiler).338This behavior is chosen so339that the bytes of a packed struct correspond exactly to the memory layout340of the corresponding C struct.341Whether to use native byte ordering342and padding or standard formats depends on the application.</p>343<p id="index-1">Alternatively, the first character of the format string can be used to indicate344the byte order, size and alignment of the packed data, according to the345following table:</p>346<table class="docutils align-default">347<thead>348<tr class="row-odd"><th class="head"><p>Character</p></th>349<th class="head"><p>Byte order</p></th>350<th class="head"><p>Size</p></th>351<th class="head"><p>Alignment</p></th>352</tr>353</thead>354<tbody>355<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">@</span></code></p></td>356<td><p>native</p></td>357<td><p>native</p></td>358<td><p>native</p></td>359</tr>360<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">=</span></code></p></td>361<td><p>native</p></td>362<td><p>standard</p></td>363<td><p>none</p></td>364</tr>365<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre"><</span></code></p></td>366<td><p>little-endian</p></td>367<td><p>standard</p></td>368<td><p>none</p></td>369</tr>370<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">></span></code></p></td>371<td><p>big-endian</p></td>372<td><p>standard</p></td>373<td><p>none</p></td>374</tr>375<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">!</span></code></p></td>376<td><p>network (= big-endian)</p></td>377<td><p>standard</p></td>378<td><p>none</p></td>379</tr>380</tbody>381</table>382<p>If the first character is not one of these, <code class="docutils literal notranslate"><span class="pre">'@'</span></code> is assumed.</p>383<div class="admonition note">384<p class="admonition-title">Note</p>385<p>The number 1023 (<code class="docutils literal notranslate"><span class="pre">0x3ff</span></code> in hexadecimal) has the following byte representations:</p>386<ul class="simple">387<li><p><code class="docutils literal notranslate"><span class="pre">03</span> <span class="pre">ff</span></code> in big-endian (<code class="docutils literal notranslate"><span class="pre">></span></code>)</p></li>388<li><p><code class="docutils literal notranslate"><span class="pre">ff</span> <span class="pre">03</span></code> in little-endian (<code class="docutils literal notranslate"><span class="pre"><</span></code>)</p></li>389</ul>390<p>Python example:</p>391<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">struct</span>392<span class="gp">>>> </span><span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s1">'>h'</span><span class="p">,</span> <span class="mi">1023</span><span class="p">)</span>393<span class="go">b'\x03\xff'</span>394<span class="gp">>>> </span><span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s1">'<h'</span><span class="p">,</span> <span class="mi">1023</span><span class="p">)</span>395<span class="go">b'\xff\x03'</span>396</pre></div>397</div>398</div>399<p>Native byte order is big-endian or little-endian, depending on the400host system. For example, Intel x86, AMD64 (x86-64), and Apple M1 are401little-endian; IBM z and many legacy architectures are big-endian.402Use <a class="reference internal" href="sys.html#sys.byteorder" title="sys.byteorder"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.byteorder</span></code></a> to check the endianness of your system.</p>403<p>Native size and alignment are determined using the C compiler’s404<code class="docutils literal notranslate"><span class="pre">sizeof</span></code> expression. This is always combined with native byte order.</p>405<p>Standard size depends only on the format character; see the table in406the <a class="reference internal" href="#format-characters"><span class="std std-ref">Format Characters</span></a> section.</p>407<p>Note the difference between <code class="docutils literal notranslate"><span class="pre">'@'</span></code> and <code class="docutils literal notranslate"><span class="pre">'='</span></code>: both use native byte order, but408the size and alignment of the latter is standardized.</p>409<p>The form <code class="docutils literal notranslate"><span class="pre">'!'</span></code> represents the network byte order which is always big-endian410as defined in <a class="reference external" href="https://datatracker.ietf.org/doc/html/rfc1700">IETF RFC 1700</a>.</p>411<p>There is no way to indicate non-native byte order (force byte-swapping); use the412appropriate choice of <code class="docutils literal notranslate"><span class="pre">'<'</span></code> or <code class="docutils literal notranslate"><span class="pre">'>'</span></code>.</p>413<p>Notes:</p>414<ol class="arabic simple">415<li><p>Padding is only automatically added between successive structure members.416No padding is added at the beginning or the end of the encoded struct.</p></li>417<li><p>No padding is added when using non-native size and alignment, e.g.418with ‘<’, ‘>’, ‘=’, and ‘!’.</p></li>419<li><p>To align the end of a structure to the alignment requirement of a420particular type, end the format with the code for that type with a repeat421count of zero. See <a class="reference internal" href="#struct-examples"><span class="std std-ref">Examples</span></a>.</p></li>422</ol>423</section>424<section id="format-characters">425<span id="id1"></span><h3>Format Characters<a class="headerlink" href="#format-characters" title="Link to this heading">¶</a></h3>426<p>Format characters have the following meaning; the conversion between C and427Python values should be obvious given their types. The ‘Standard size’ column428refers to the size of the packed value in bytes when using standard size; that429is, when the format string starts with one of <code class="docutils literal notranslate"><span class="pre">'<'</span></code>, <code class="docutils literal notranslate"><span class="pre">'>'</span></code>, <code class="docutils literal notranslate"><span class="pre">'!'</span></code> or430<code class="docutils literal notranslate"><span class="pre">'='</span></code>. When using native size, the size of the packed value is431platform-dependent.</p>432<table class="docutils align-default">433<thead>434<tr class="row-odd"><th class="head"><p>Format</p></th>435<th class="head"><p>C Type</p></th>436<th class="head"><p>Python type</p></th>437<th class="head"><p>Standard size</p></th>438<th class="head"><p>Notes</p></th>439</tr>440</thead>441<tbody>442<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">x</span></code></p></td>443<td><p>pad byte</p></td>444<td><p>no value</p></td>445<td></td>446<td><p>(7)</p></td>447</tr>448<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">c</span></code></p></td>449<td><p><span class="c-expr sig sig-inline c"><span class="kt">char</span></span></p></td>450<td><p>bytes of length 1</p></td>451<td><p>1</p></td>452<td></td>453</tr>454<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">b</span></code></p></td>455<td><p><span class="c-expr sig sig-inline c"><span class="kt">signed</span><span class="w"> </span><span class="kt">char</span></span></p></td>456<td><p>integer</p></td>457<td><p>1</p></td>458<td><p>(1), (2)</p></td>459</tr>460<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">B</span></code></p></td>461<td><p><span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">char</span></span></p></td>462<td><p>integer</p></td>463<td><p>1</p></td>464<td><p>(2)</p></td>465</tr>466<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">?</span></code></p></td>467<td><p><span class="c-expr sig sig-inline c"><span class="kt">_Bool</span></span></p></td>468<td><p>bool</p></td>469<td><p>1</p></td>470<td><p>(1)</p></td>471</tr>472<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">h</span></code></p></td>473<td><p><span class="c-expr sig sig-inline c"><span class="kt">short</span></span></p></td>474<td><p>integer</p></td>475<td><p>2</p></td>476<td><p>(2)</p></td>477</tr>478<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">H</span></code></p></td>479<td><p><span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">short</span></span></p></td>480<td><p>integer</p></td>481<td><p>2</p></td>482<td><p>(2)</p></td>483</tr>484<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">i</span></code></p></td>485<td><p><span class="c-expr sig sig-inline c"><span class="kt">int</span></span></p></td>486<td><p>integer</p></td>487<td><p>4</p></td>488<td><p>(2)</p></td>489</tr>490<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">I</span></code></p></td>491<td><p><span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span></span></p></td>492<td><p>integer</p></td>493<td><p>4</p></td>494<td><p>(2)</p></td>495</tr>496<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">l</span></code></p></td>497<td><p><span class="c-expr sig sig-inline c"><span class="kt">long</span></span></p></td>498<td><p>integer</p></td>499<td><p>4</p></td>500<td><p>(2)</p></td>501</tr>502<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">L</span></code></p></td>503<td><p><span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span></span></p></td>504<td><p>integer</p></td>505<td><p>4</p></td>506<td><p>(2)</p></td>507</tr>508<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">q</span></code></p></td>509<td><p><span class="c-expr sig sig-inline c"><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span></p></td>510<td><p>integer</p></td>511<td><p>8</p></td>512<td><p>(2)</p></td>513</tr>514<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">Q</span></code></p></td>515<td><p><span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span></p></td>516<td><p>integer</p></td>517<td><p>8</p></td>518<td><p>(2)</p></td>519</tr>520<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">n</span></code></p></td>521<td><p><code class="xref c c-type docutils literal notranslate"><span class="pre">ssize_t</span></code></p></td>522<td><p>integer</p></td>523<td></td>524<td><p>(3)</p></td>525</tr>526<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">N</span></code></p></td>527<td><p><code class="xref c c-type docutils literal notranslate"><span class="pre">size_t</span></code></p></td>528<td><p>integer</p></td>529<td></td>530<td><p>(3)</p></td>531</tr>532<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">e</span></code></p></td>533<td><p>(6)</p></td>534<td><p>float</p></td>535<td><p>2</p></td>536<td><p>(4)</p></td>537</tr>538<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">f</span></code></p></td>539<td><p><span class="c-expr sig sig-inline c"><span class="kt">float</span></span></p></td>540<td><p>float</p></td>541<td><p>4</p></td>542<td><p>(4)</p></td>543</tr>544<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">d</span></code></p></td>545<td><p><span class="c-expr sig sig-inline c"><span class="kt">double</span></span></p></td>546<td><p>float</p></td>547<td><p>8</p></td>548<td><p>(4)</p></td>549</tr>550<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">F</span></code></p></td>551<td><p><span class="c-expr sig sig-inline c"><span class="kt">float</span><span class="w"> </span><span class="kt">complex</span></span></p></td>552<td><p>complex</p></td>553<td><p>8</p></td>554<td><p>(10)</p></td>555</tr>556<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">D</span></code></p></td>557<td><p><span class="c-expr sig sig-inline c"><span class="kt">double</span><span class="w"> </span><span class="kt">complex</span></span></p></td>558<td><p>complex</p></td>559<td><p>16</p></td>560<td><p>(10)</p></td>561</tr>562<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">s</span></code></p></td>563<td><p><span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">[</span><span class="p">]</span></span></p></td>564<td><p>bytes</p></td>565<td></td>566<td><p>(9)</p></td>567</tr>568<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">p</span></code></p></td>569<td><p><span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">[</span><span class="p">]</span></span></p></td>570<td><p>bytes</p></td>571<td></td>572<td><p>(8)</p></td>573</tr>574<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">P</span></code></p></td>575<td><p><span class="c-expr sig sig-inline c"><span class="kt">void</span><span class="p">*</span></span></p></td>576<td><p>integer</p></td>577<td></td>578<td><p>(5)</p></td>579</tr>580</tbody>581</table>582<div class="versionchanged">583<p><span class="versionmodified changed">Changed in version 3.3: </span>Added support for the <code class="docutils literal notranslate"><span class="pre">'n'</span></code> and <code class="docutils literal notranslate"><span class="pre">'N'</span></code> formats.</p>584</div>585<div class="versionchanged">586<p><span class="versionmodified changed">Changed in version 3.6: </span>Added support for the <code class="docutils literal notranslate"><span class="pre">'e'</span></code> format.</p>587</div>588<div class="versionchanged">589<p><span class="versionmodified changed">Changed in version 3.14: </span>Added support for the <code class="docutils literal notranslate"><span class="pre">'F'</span></code> and <code class="docutils literal notranslate"><span class="pre">'D'</span></code> formats.</p>590</div>591<p>Notes:</p>592<ol class="arabic">593<li><p id="index-2">The <code class="docutils literal notranslate"><span class="pre">'?'</span></code> conversion code corresponds to the <span class="c-expr sig sig-inline c"><span class="kt">_Bool</span></span> type594defined by C standards since C99. In standard mode, it is595represented by one byte.</p>596</li>597<li><p>When attempting to pack a non-integer using any of the integer conversion598codes, if the non-integer has a <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method then that method is599called to convert the argument to an integer before packing.</p>600<div class="versionchanged">601<p><span class="versionmodified changed">Changed in version 3.2: </span>Added use of the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method for non-integers.</p>602</div>603</li>604<li><p>The <code class="docutils literal notranslate"><span class="pre">'n'</span></code> and <code class="docutils literal notranslate"><span class="pre">'N'</span></code> conversion codes are only available for the native605size (selected as the default or with the <code class="docutils literal notranslate"><span class="pre">'@'</span></code> byte order character).606For the standard size, you can use whichever of the other integer formats607fits your application.</p></li>608<li><p>For the <code class="docutils literal notranslate"><span class="pre">'f'</span></code>, <code class="docutils literal notranslate"><span class="pre">'d'</span></code> and <code class="docutils literal notranslate"><span class="pre">'e'</span></code> conversion codes, the packed609representation uses the IEEE 754 binary32, binary64 or binary16 format (for610<code class="docutils literal notranslate"><span class="pre">'f'</span></code>, <code class="docutils literal notranslate"><span class="pre">'d'</span></code> or <code class="docutils literal notranslate"><span class="pre">'e'</span></code> respectively), regardless of the floating-point611format used by the platform.</p></li>612<li><p>The <code class="docutils literal notranslate"><span class="pre">'P'</span></code> format character is only available for the native byte ordering613(selected as the default or with the <code class="docutils literal notranslate"><span class="pre">'@'</span></code> byte order character). The byte614order character <code class="docutils literal notranslate"><span class="pre">'='</span></code> chooses to use little- or big-endian ordering based615on the host system. The struct module does not interpret this as native616ordering, so the <code class="docutils literal notranslate"><span class="pre">'P'</span></code> format is not available.</p></li>617<li><p>The IEEE 754 binary16 “half precision” type was introduced in the 2008618revision of the <a class="reference external" href="https://en.wikipedia.org/wiki/IEEE_754-2008_revision">IEEE 754 standard</a>. It has a sign619bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored),620and can represent numbers between approximately <code class="docutils literal notranslate"><span class="pre">6.1e-05</span></code> and <code class="docutils literal notranslate"><span class="pre">6.5e+04</span></code>621at full precision. This type is not widely supported by C compilers: on a622typical machine, an unsigned short can be used for storage, but not for math623operations. See the Wikipedia page on the <a class="reference external" href="https://en.wikipedia.org/wiki/Half-precision_floating-point_format">half-precision floating-point624format</a> for more information.</p></li>625<li><p>When packing, <code class="docutils literal notranslate"><span class="pre">'x'</span></code> inserts one NUL byte.</p></li>626<li><p>The <code class="docutils literal notranslate"><span class="pre">'p'</span></code> format character encodes a “Pascal string”, meaning a short627variable-length string stored in a <em>fixed number of bytes</em>, given by the count.628The first byte stored is the length of the string, or 255, whichever is629smaller. The bytes of the string follow. If the string passed in to630<a class="reference internal" href="#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> is too long (longer than the count minus 1), only the leading631<code class="docutils literal notranslate"><span class="pre">count-1</span></code> bytes of the string are stored. If the string is shorter than632<code class="docutils literal notranslate"><span class="pre">count-1</span></code>, it is padded with null bytes so that exactly count bytes in all633are used. Note that for <a class="reference internal" href="#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a>, the <code class="docutils literal notranslate"><span class="pre">'p'</span></code> format character consumes634<code class="docutils literal notranslate"><span class="pre">count</span></code> bytes, but that the string returned can never contain more than 255635bytes.</p></li>636<li><p>For the <code class="docutils literal notranslate"><span class="pre">'s'</span></code> format character, the count is interpreted as the length of the637bytes, not a repeat count like for the other format characters; for example,638<code class="docutils literal notranslate"><span class="pre">'10s'</span></code> means a single 10-byte string mapping to or from a single639Python byte string, while <code class="docutils literal notranslate"><span class="pre">'10c'</span></code> means 10640separate one byte character elements (e.g., <code class="docutils literal notranslate"><span class="pre">cccccccccc</span></code>) mapping641to or from ten different Python byte objects. (See <a class="reference internal" href="#struct-examples"><span class="std std-ref">Examples</span></a>642for a concrete demonstration of the difference.)643If a count is not given, it defaults to 1. For packing, the string is644truncated or padded with null bytes as appropriate to make it fit. For645unpacking, the resulting bytes object always has exactly the specified number646of bytes. As a special case, <code class="docutils literal notranslate"><span class="pre">'0s'</span></code> means a single, empty string (while647<code class="docutils literal notranslate"><span class="pre">'0c'</span></code> means 0 characters).</p></li>648<li><p>For the <code class="docutils literal notranslate"><span class="pre">'F'</span></code> and <code class="docutils literal notranslate"><span class="pre">'D'</span></code> format characters, the packed representation uses649the IEEE 754 binary32 and binary64 format for components of the complex650number, regardless of the floating-point format used by the platform.651Note that complex types (<code class="docutils literal notranslate"><span class="pre">F</span></code> and <code class="docutils literal notranslate"><span class="pre">D</span></code>) are available unconditionally,652despite complex types being an optional feature in C.653As specified in the C11 standard, each complex type is represented by a654two-element C array containing, respectively, the real and imaginary parts.</p></li>655</ol>656<p>A format character may be preceded by an integral repeat count. For example,657the format string <code class="docutils literal notranslate"><span class="pre">'4h'</span></code> means exactly the same as <code class="docutils literal notranslate"><span class="pre">'hhhh'</span></code>.</p>658<p>Whitespace characters between formats are ignored; a count and its format must659not contain whitespace though.</p>660<p>When packing a value <code class="docutils literal notranslate"><span class="pre">x</span></code> using one of the integer formats (<code class="docutils literal notranslate"><span class="pre">'b'</span></code>,661<code class="docutils literal notranslate"><span class="pre">'B'</span></code>, <code class="docutils literal notranslate"><span class="pre">'h'</span></code>, <code class="docutils literal notranslate"><span class="pre">'H'</span></code>, <code class="docutils literal notranslate"><span class="pre">'i'</span></code>, <code class="docutils literal notranslate"><span class="pre">'I'</span></code>, <code class="docutils literal notranslate"><span class="pre">'l'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code>,662<code class="docutils literal notranslate"><span class="pre">'q'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Q'</span></code>), if <code class="docutils literal notranslate"><span class="pre">x</span></code> is outside the valid range for that format663then <a class="reference internal" href="#struct.error" title="struct.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">struct.error</span></code></a> is raised.</p>664<div class="versionchanged">665<p><span class="versionmodified changed">Changed in version 3.1: </span>Previously, some of the integer formats wrapped out-of-range values and666raised <a class="reference internal" href="exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> instead of <a class="reference internal" href="#struct.error" title="struct.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">struct.error</span></code></a>.</p>667</div>668<p id="index-3">For the <code class="docutils literal notranslate"><span class="pre">'?'</span></code> format character, the return value is either <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or669<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. When packing, the truth value of the argument object is used.670Either 0 or 1 in the native or standard bool representation will be packed, and671any non-zero value will be <code class="docutils literal notranslate"><span class="pre">True</span></code> when unpacking.</p>672</section>673<section id="examples">674<span id="struct-examples"></span><h3>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h3>675<div class="admonition note">676<p class="admonition-title">Note</p>677<p>Native byte order examples (designated by the <code class="docutils literal notranslate"><span class="pre">'@'</span></code> format prefix or678lack of any prefix character) may not match what the reader’s679machine produces as680that depends on the platform and compiler.</p>681</div>682<p>Pack and unpack integers of three different sizes, using big endian683ordering:</p>684<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">struct</span><span class="w"> </span><span class="kn">import</span> <span class="o">*</span>685<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s2">">bhl"</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>686<span class="go">b'\x01\x00\x02\x00\x00\x00\x03'</span>687<span class="gp">>>> </span><span class="n">unpack</span><span class="p">(</span><span class="s1">'>bhl'</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'</span><span class="se">\x01\x00\x02\x00\x00\x00\x03</span><span class="s1">'</span><span class="p">)</span>688<span class="go">(1, 2, 3)</span>689<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'>bhl'</span><span class="p">)</span>690<span class="go">7</span>691</pre></div>692</div>693<p>Attempt to pack an integer which is too large for the defined field:</p>694<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s2">">h"</span><span class="p">,</span> <span class="mi">99999</span><span class="p">)</span>695<span class="gt">Traceback (most recent call last):</span>696 File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>697<span class="gr">struct.error</span>: <span class="n">'h' format requires -32768 <= number <= 32767</span>698</pre></div>699</div>700<p>Demonstrate the difference between <code class="docutils literal notranslate"><span class="pre">'s'</span></code> and <code class="docutils literal notranslate"><span class="pre">'c'</span></code> format701characters:</p>702<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s2">"@ccc"</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'1'</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'2'</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'3'</span><span class="p">)</span>703<span class="go">b'123'</span>704<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s2">"@3s"</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'123'</span><span class="p">)</span>705<span class="go">b'123'</span>706</pre></div>707</div>708<p>Unpacked fields can be named by assigning them to variables or by wrapping709the result in a named tuple:</p>710<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">record</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">'raymond </span><span class="se">\x32\x12\x08\x01\x08</span><span class="s1">'</span>711<span class="gp">>>> </span><span class="n">name</span><span class="p">,</span> <span class="n">serialnum</span><span class="p">,</span> <span class="n">school</span><span class="p">,</span> <span class="n">gradelevel</span> <span class="o">=</span> <span class="n">unpack</span><span class="p">(</span><span class="s1">'<10sHHb'</span><span class="p">,</span> <span class="n">record</span><span class="p">)</span>712 713<span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">collections</span><span class="w"> </span><span class="kn">import</span> <span class="n">namedtuple</span>714<span class="gp">>>> </span><span class="n">Student</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Student'</span><span class="p">,</span> <span class="s1">'name serialnum school gradelevel'</span><span class="p">)</span>715<span class="gp">>>> </span><span class="n">Student</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">unpack</span><span class="p">(</span><span class="s1">'<10sHHb'</span><span class="p">,</span> <span class="n">record</span><span class="p">))</span>716<span class="go">Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)</span>717</pre></div>718</div>719<p>The ordering of format characters may have an impact on size in native720mode since padding is implicit. In standard mode, the user is721responsible for inserting any desired padding.722Note in723the first <code class="docutils literal notranslate"><span class="pre">pack</span></code> call below that three NUL bytes were added after the724packed <code class="docutils literal notranslate"><span class="pre">'#'</span></code> to align the following integer on a four-byte boundary.725In this example, the output was produced on a little endian machine:</p>726<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@ci'</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'#'</span><span class="p">,</span> <span class="mh">0x12131415</span><span class="p">)</span>727<span class="go">b'#\x00\x00\x00\x15\x14\x13\x12'</span>728<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@ic'</span><span class="p">,</span> <span class="mh">0x12131415</span><span class="p">,</span> <span class="sa">b</span><span class="s1">'#'</span><span class="p">)</span>729<span class="go">b'\x15\x14\x13\x12#'</span>730<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@ci'</span><span class="p">)</span>731<span class="go">8</span>732<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@ic'</span><span class="p">)</span>733<span class="go">5</span>734</pre></div>735</div>736<p>The following format <code class="docutils literal notranslate"><span class="pre">'llh0l'</span></code> results in two pad bytes being added737at the end, assuming the platform’s longs are aligned on 4-byte boundaries:</p>738<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>739<span class="go">b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'</span>740</pre></div>741</div>742<div class="admonition seealso">743<p class="admonition-title">See also</p>744<dl class="simple">745<dt>Module <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a></dt><dd><p>Packed binary storage of homogeneous data.</p>746</dd>747<dt>Module <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></dt><dd><p>JSON encoder and decoder.</p>748</dd>749<dt>Module <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a></dt><dd><p>Python object serialization.</p>750</dd>751</dl>752</div>753</section>754</section>755<section id="applications">756<span id="id2"></span><h2>Applications<a class="headerlink" href="#applications" title="Link to this heading">¶</a></h2>757<p>Two main applications for the <code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> module exist, data758interchange between Python and C code within an application or another759application compiled using the same compiler (<a class="reference internal" href="#struct-native-formats"><span class="std std-ref">native formats</span></a>), and760data interchange between applications using agreed upon data layout761(<a class="reference internal" href="#struct-standard-formats"><span class="std std-ref">standard formats</span></a>). Generally speaking, the format strings762constructed for these two domains are distinct.</p>763<section id="native-formats">764<span id="struct-native-formats"></span><h3>Native Formats<a class="headerlink" href="#native-formats" title="Link to this heading">¶</a></h3>765<p>When constructing format strings which mimic native layouts, the766compiler and machine architecture determine byte ordering and padding.767In such cases, the <code class="docutils literal notranslate"><span class="pre">@</span></code> format character should be used to specify768native byte ordering and data sizes. Internal pad bytes are normally inserted769automatically. It is possible that a zero-repeat format code will be770needed at the end of a format string to round up to the correct771byte boundary for proper alignment of consecutive chunks of data.</p>772<p>Consider these two simple examples (on a 64-bit, little-endian773machine):</p>774<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@lhl'</span><span class="p">)</span>775<span class="go">24</span>776<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@llh'</span><span class="p">)</span>777<span class="go">18</span>778</pre></div>779</div>780<p>Data is not padded to an 8-byte boundary at the end of the second781format string without the use of extra padding. A zero-repeat format782code solves that problem:</p>783<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">)</span>784<span class="go">24</span>785</pre></div>786</div>787<p>The <code class="docutils literal notranslate"><span class="pre">'x'</span></code> format code can be used to specify the repeat, but for788native formats it is better to use a zero-repeat format like <code class="docutils literal notranslate"><span class="pre">'0l'</span></code>.</p>789<p>By default, native byte ordering and alignment is used, but it is790better to be explicit and use the <code class="docutils literal notranslate"><span class="pre">'@'</span></code> prefix character.</p>791</section>792<section id="standard-formats">793<span id="struct-standard-formats"></span><h3>Standard Formats<a class="headerlink" href="#standard-formats" title="Link to this heading">¶</a></h3>794<p>When exchanging data beyond your process such as networking or storage,795be precise. Specify the exact byte order, size, and alignment. Do796not assume they match the native order of a particular machine.797For example, network byte order is big-endian, while many popular CPUs798are little-endian. By defining this explicitly, the user need not799care about the specifics of the platform their code is running on.800The first character should typically be <code class="docutils literal notranslate"><span class="pre"><</span></code> or <code class="docutils literal notranslate"><span class="pre">></span></code>801(or <code class="docutils literal notranslate"><span class="pre">!</span></code>). Padding is the responsibility of the programmer. The802zero-repeat format character won’t work. Instead, the user must803explicitly add <code class="docutils literal notranslate"><span class="pre">'x'</span></code> pad bytes where needed. Revisiting the804examples from the previous section, we have:</p>805<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'<qh6xq'</span><span class="p">)</span>806<span class="go">24</span>807<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'<qh6xq'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">==</span> <span class="n">pack</span><span class="p">(</span><span class="s1">'@lhl'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>808<span class="go">True</span>809<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@llh'</span><span class="p">)</span>810<span class="go">18</span>811<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@llh'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">==</span> <span class="n">pack</span><span class="p">(</span><span class="s1">'<qqh'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>812<span class="go">True</span>813<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'<qqh6x'</span><span class="p">)</span>814<span class="go">24</span>815<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">)</span>816<span class="go">24</span>817<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">==</span> <span class="n">pack</span><span class="p">(</span><span class="s1">'<qqh6x'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>818<span class="go">True</span>819</pre></div>820</div>821<p>The above results (executed on a 64-bit machine) aren’t guaranteed to822match when executed on different machines. For example, the examples823below were executed on a 32-bit machine:</p>824<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'<qqh6x'</span><span class="p">)</span>825<span class="go">24</span>826<span class="gp">>>> </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">)</span>827<span class="go">12</span>828<span class="gp">>>> </span><span class="n">pack</span><span class="p">(</span><span class="s1">'@llh0l'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="o">==</span> <span class="n">pack</span><span class="p">(</span><span class="s1">'<qqh6x'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>829<span class="go">False</span>830</pre></div>831</div>832</section>833</section>834<section id="classes">835<span id="struct-objects"></span><h2>Classes<a class="headerlink" href="#classes" title="Link to this heading">¶</a></h2>836<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> module also defines the following type:</p>837<dl class="py class">838<dt class="sig sig-object py" id="struct.Struct">839<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">struct.</span></span><span class="sig-name descname"><span class="pre">Struct</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">format</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct" title="Link to this definition">¶</a></dt>840<dd><p>Return a new Struct object which writes and reads binary data according to841the format string <em>format</em>. Creating a <code class="docutils literal notranslate"><span class="pre">Struct</span></code> object once and calling its842methods is more efficient than calling module-level functions with the843same format since the format string is only compiled once.</p>844<div class="admonition note">845<p class="admonition-title">Note</p>846<p>The compiled versions of the most recent format strings passed to847the module-level functions are cached, so programs that use only a few848format strings needn’t worry about reusing a single <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code>849instance.</p>850</div>851<p>Compiled Struct objects support the following methods and attributes:</p>852<dl class="py method">853<dt class="sig sig-object py" id="struct.Struct.pack">854<span class="sig-name descname"><span class="pre">pack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">v1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v2</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.pack" title="Link to this definition">¶</a></dt>855<dd><p>Identical to the <a class="reference internal" href="#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> function, using the compiled format.856(<code class="docutils literal notranslate"><span class="pre">len(result)</span></code> will equal <a class="reference internal" href="#struct.Struct.size" title="struct.Struct.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a>.)</p>857</dd></dl>858 859<dl class="py method">860<dt class="sig sig-object py" id="struct.Struct.pack_into">861<span class="sig-name descname"><span class="pre">pack_into</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">offset</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">v2</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.pack_into" title="Link to this definition">¶</a></dt>862<dd><p>Identical to the <a class="reference internal" href="#struct.pack_into" title="struct.pack_into"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack_into()</span></code></a> function, using the compiled format.</p>863</dd></dl>864 865<dl class="py method">866<dt class="sig sig-object py" id="struct.Struct.unpack">867<span class="sig-name descname"><span class="pre">unpack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.unpack" title="Link to this definition">¶</a></dt>868<dd><p>Identical to the <a class="reference internal" href="#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> function, using the compiled format.869The buffer’s size in bytes must equal <a class="reference internal" href="#struct.Struct.size" title="struct.Struct.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a>.</p>870</dd></dl>871 872<dl class="py method">873<dt class="sig sig-object py" id="struct.Struct.unpack_from">874<span class="sig-name descname"><span class="pre">unpack_from</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">offset</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.unpack_from" title="Link to this definition">¶</a></dt>875<dd><p>Identical to the <a class="reference internal" href="#struct.unpack_from" title="struct.unpack_from"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack_from()</span></code></a> function, using the compiled format.876The buffer’s size in bytes, starting at position <em>offset</em>, must be at least877<a class="reference internal" href="#struct.Struct.size" title="struct.Struct.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a>.</p>878</dd></dl>879 880<dl class="py method">881<dt class="sig sig-object py" id="struct.Struct.iter_unpack">882<span class="sig-name descname"><span class="pre">iter_unpack</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.iter_unpack" title="Link to this definition">¶</a></dt>883<dd><p>Identical to the <a class="reference internal" href="#struct.iter_unpack" title="struct.iter_unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter_unpack()</span></code></a> function, using the compiled format.884The buffer’s size in bytes must be a multiple of <a class="reference internal" href="#struct.Struct.size" title="struct.Struct.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a>.</p>885<div class="versionadded">886<p><span class="versionmodified added">Added in version 3.4.</span></p>887</div>888</dd></dl>889 890<dl class="py attribute">891<dt class="sig sig-object py" id="struct.Struct.format">892<span class="sig-name descname"><span class="pre">format</span></span><a class="headerlink" href="#struct.Struct.format" title="Link to this definition">¶</a></dt>893<dd><p>The format string used to construct this Struct object.</p>894<div class="versionchanged">895<p><span class="versionmodified changed">Changed in version 3.7: </span>The format string type is now <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> instead of <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>.</p>896</div>897</dd></dl>898 899<dl class="py attribute">900<dt class="sig sig-object py" id="struct.Struct.size">901<span class="sig-name descname"><span class="pre">size</span></span><a class="headerlink" href="#struct.Struct.size" title="Link to this definition">¶</a></dt>902<dd><p>The calculated size of the struct (and hence of the bytes object produced903by the <a class="reference internal" href="#struct.pack" title="struct.pack"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack()</span></code></a> method) corresponding to <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">format</span></code></a>.</p>904</dd></dl>905 906<div class="versionchanged">907<p><span class="versionmodified changed">Changed in version 3.13: </span>The <em>repr()</em> of structs has changed. It908is now:</p>909<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Struct</span><span class="p">(</span><span class="s1">'i'</span><span class="p">)</span>910<span class="go">Struct('i')</span>911</pre></div>912</div>913</div>914</dd></dl>915 916</section>917</section>918 919 920 <div class="clearer"></div>921 </div>922 </div>923 </div>924 <div class="sphinxsidebar" role="navigation" aria-label="Main">925 <div class="sphinxsidebarwrapper">926 <div>927 <h3><a href="../contents.html">Table of Contents</a></h3>928 <ul>929<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> — Interpret bytes as packed binary data</a><ul>930<li><a class="reference internal" href="#functions-and-exceptions">Functions and Exceptions</a></li>931<li><a class="reference internal" href="#format-strings">Format Strings</a><ul>932<li><a class="reference internal" href="#byte-order-size-and-alignment">Byte Order, Size, and Alignment</a></li>933<li><a class="reference internal" href="#format-characters">Format Characters</a></li>934<li><a class="reference internal" href="#examples">Examples</a></li>935</ul>936</li>937<li><a class="reference internal" href="#applications">Applications</a><ul>938<li><a class="reference internal" href="#native-formats">Native Formats</a></li>939<li><a class="reference internal" href="#standard-formats">Standard Formats</a></li>940</ul>941</li>942<li><a class="reference internal" href="#classes">Classes</a></li>943</ul>944</li>945</ul>946 947 </div>948 <div>949 <h4>Previous topic</h4>950 <p class="topless"><a href="binary.html"951 title="previous chapter">Binary Data Services</a></p>952 </div>953 <div>954 <h4>Next topic</h4>955 <p class="topless"><a href="codecs.html"956 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a></p>957 </div>958 <script>959 document.addEventListener('DOMContentLoaded', () => {960 const title = document.querySelector('meta[property="og:title"]').content;961 const elements = document.querySelectorAll('.improvepage');962 const pageurl = window.location.href.split('?')[0];963 elements.forEach(element => {964 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));965 url.searchParams.set('pagetitle', title);966 url.searchParams.set('pageurl', pageurl);967 url.searchParams.set('pagesource', "library/struct.rst");968 element.href = url.toString();969 });970 });971 </script>972 <div role="note" aria-label="source link">973 <h3>This page</h3>974 <ul class="this-page-menu">975 <li><a href="../bugs.html">Report a bug</a></li>976 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>977 <li>978 <a href="https://github.com/python/cpython/blob/main/Doc/library/struct.rst?plain=1"979 rel="nofollow">Show source980 </a>981 </li>982 983 </ul>984 </div>985 </div>986<div id="sidebarbutton" title="Collapse sidebar">987<span>«</span>988</div>989 990 </div>991 <div class="clearer"></div>992 </div> 993 <div class="related" role="navigation" aria-label="Related">994 <h3>Navigation</h3>995 <ul>996 <li class="right" style="margin-right: 10px">997 <a href="../genindex.html" title="General Index"998 >index</a></li>999 <li class="right" >1000 <a href="../py-modindex.html" title="Python Module Index"1001 >modules</a> |</li>1002 <li class="right" >1003 <a href="codecs.html" title="codecs — Codec registry and base classes"1004 >next</a> |</li>1005 <li class="right" >1006 <a href="binary.html" title="Binary Data Services"1007 >previous</a> |</li>1008 1009 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>1010 <li><a href="https://www.python.org/">Python</a> »</li>1011 <li class="switchers">1012 <div class="language_switcher_placeholder"></div>1013 <div class="version_switcher_placeholder"></div>1014 </li>1015 <li>1016 1017 </li>1018 <li id="cpython-language-and-version">1019 <a href="../index.html">3.15.0a6 Documentation</a> »1020 </li>1021 1022 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>1023 <li class="nav-item nav-item-2"><a href="binary.html" >Binary Data Services</a> »</li>1024 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code> — Interpret bytes as packed binary data</a></li>1025 <li class="right">1026 1027 1028 <div class="inline-search" role="search">1029 <form class="inline-search" action="../search.html" method="get">1030 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">1031 <input type="submit" value="Go">1032 </form>1033 </div>1034 |1035 </li>1036 <li class="right">1037<label class="theme-selector-label">1038 Theme1039 <select class="theme-selector" oninput="activateTheme(this.value)">1040 <option value="auto" selected>Auto</option>1041 <option value="light">Light</option>1042 <option value="dark">Dark</option>1043 </select>1044</label> |</li>1045 1046 </ul>1047 </div> 1048 <div class="footer">1049 © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.1050 <br>1051 This page is licensed under the Python Software Foundation License Version 2.1052 <br>1053 Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.1054 <br>1055 1056 See <a href="/license.html">History and License</a> for more information.<br>1057 1058 1059 <br>1060 1061 The Python Software Foundation is a non-profit corporation.1062<a href="https://www.python.org/psf/donations/">Please donate.</a>1063<br>1064 <br>1065 Last updated on Mar 10, 2026 (08:58 UTC).1066 1067 <a href="/bugs.html">Found a bug</a>?1068 1069 <br>1070 1071 Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.1072 </div>1073 1074 </body>1075</html>