title: Unpack binary data with python
body: <p>I would like to unpack an array of binary data to <code>uint16</code> data with Python.</p>
  
  <p>Internet is full of examples using <code>struct.unpack</code> but only examples dealing with binary array of size 4. </p>
  
  <p>Most of these examples are as follow (<code>B</code> is a binary array from a file)</p>
  
  <pre><code>U = struct.unpack("HH",B[0:4]);
  </code></pre>
  
  <p>So i tried to unpack an array of size 6:</p>
  
  <pre><code>U = struct.unpack("HHH",B[0:6]);
  </code></pre>
  
  <p>It works.</p>
  
  <p>But how to do if I want to unpack an array of size <code>L</code> (<code>L</code> is pair)?
  I tried that:</p>
  
  <pre><code>U = struct.unpack("H"*(L/2),B[0:L]);
  </code></pre>
  
  <p>but it doesn't work, prompter gives me an error (for <code>L=512</code> for example):</p>
  
  <pre><code>struct.error: unpack requires a string argument of length 512
  </code></pre>
  
  <p>This message is strange because if i want to unpack a binary array to <code>uint16</code>, I need a string <code>"HHH...HHH"</code> of half size of this array...</p>
  
  <p>I would be very grateful if someone could provide me with some help.</p>
  
  <hr>
  
  <p>I progress a little bit... In fact, i tried:</p>
  
  <pre><code>U = struct.unpack("H"*8,B[0:8]); 
  </code></pre>
  
  <p>It works.</p>
  
  <pre><code>U = struct.unpack("H"*10,B[0:10]);
  </code></pre>
  
  <p>It works.</p>
  
  <pre><code>U = struct.unpack("H"*222,B[0:444]);
  </code></pre>
  
  <p>It still works</p>
  
  <pre><code>U = struct.unpack("H"*223,B[0:446]);
  </code></pre>
  
  <p>It doesn't work! and it never works for size bigger than 446</p>
  
  <p>Hope it will help anyone to answer me.</p>
  
  <hr>
  
  <p>@MarkRansom I checked len(B) and in fact, the length is 444. I was so sure that B is an array of size 512 because B comes from :  <code>B = f.read(512)</code> where F is a 8000-bytes-size file. So a problem with read()... Thanks for this answer! But if someone has a help to unpack binary array of size L, i would be grateful</p>