Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:</p> <pre><code>struct { 11 char a; 012345678901 short b; ------------ char c; axbbcxxxdddd int d; }; </code></pre> <p>This structure will occupy 12 bytes of memory (x being pad bytes).</p> <p>Python works similarly (see the <a href="http://docs.python.org/library/struct.html" rel="noreferrer">struct</a> documentation):</p> <pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; struct.pack('BHBL',1,2,3,4) '\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00' &gt;&gt;&gt; struct.calcsize('BHBL') 12 </code></pre> <p>Compilers usually have a way of eliminating padding. In Python, any of =&lt;>! will eliminate padding:</p> <pre><code>&gt;&gt;&gt; struct.calcsize('=BHBL') 8 &gt;&gt;&gt; struct.pack('=BHBL',1,2,3,4) '\x01\x02\x00\x03\x04\x00\x00\x00' </code></pre> <p>Beware of letting struct handle padding. In C, these structures:</p> <pre><code>struct A { struct B { short a; int a; char b; char b; }; }; </code></pre> <p>are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:</p> <pre><code>&gt;&gt;&gt; struct.pack('LB',1,2) '\x01\x00\x00\x00\x02' &gt;&gt;&gt; struct.pack('LBLB',1,2,3,4) '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04' </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload