Why does struct.pack return these values?
<p>I have an array of signed 16bit integers that I want to convert to a little endian byte string using struct.pack in python. But I don't understand, what values struct.pack returns. Here's an example:</p>

<pre><code>&gt;&gt;&gt; bytestr = struct.pack('&lt;9h',*[45, 70, 33, 38, -6, 26, 34, 46, 57])
&gt;&gt;&gt; bytestr
&gt;&gt;&gt;&gt; '-\x00F\x00!\x00&amp;\x00\xfa\xff\x1a\x00"\x00.\x009\x00'
</code></pre>

<p>Why are there all these special characters, like '!' or '&amp;'? Shouldn't it be only a 2 character string for each byte?</p>

<p>When Python shows you a representation of a string, it'll always try to show you printable text where possible. <code>-</code>, <code>F</code>, <code>!</code>, <code>&amp;</code>, etc. are printable ASCII characters for the given bytes.</p>

<p>The output is otherwise entirely correct.</p>

<ul>
<li><p><code>45</code>, as a little-endian byte string, is represented as 0x2D 0x00 hexademimal (45 00 in decimal), but the 0x2D byte value is also the <code>-</code> character in the ASCII character set.</p></li>
<li><p><code>70</code> becomes 0x46 0x00, and 0x46 is the letter <code>F</code> in ASCII.</p></li>
<li><p><code>33</code> becomes 0x21 0x00, and 0x21 is <code>!</code></p></li>
</ul>

<p>etc.</p>

<p>If you wanted to verify the values, you could print the hexadecimal representation:</p>

<pre><code>&gt;&gt;&gt; bytestr.encode('hex')
'2d00460021002600faff1a0022002e003900'
</code></pre>

<p>or you could convert to a <a href="https://docs.python.org/2/library/functions.html#bytearray" rel="nofollow"><code>bytearray()</code> object</a>, then to a list, to get a list of integers in the range 0-255:</p>

<pre><code>&gt;&gt;&gt; list(bytearray(bytestr))
[45, 0, 70, 0, 33, 0, 38, 0, 250, 255, 26, 0, 34, 0, 46, 0, 57, 0]
</code></pre>

<p>These are just different ways of showing you what exact values are present in that byte string.</p>

python struct pack