title: How to properly pad numbers in Python's struct
body: <p>I have a tuple like this (note that first element can be of any size (big but not extremely big, ie. 2**12 - 1 is OK), and second will always be in range [0, 255]).</p>
  
  <pre class="lang-py prettyprint-override"><code>t = [(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), ...]
  </code></pre>
  
  <p>I want to store these numbers as bytes on the file system (for compression). That means I also want to later use these bits to recover the tuple. Also note that it is a requirement that the Big endian is used.</p>
  
  <pre class="lang-py prettyprint-override"><code>for idx, v in compressed:              
      if v:                              
          f.write(struct.pack("&gt;I", idx))
          f.write(struct.pack("&gt;I", v))  
  </code></pre>
  
  <p>However, when I try to get the numbers, like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>with open(filepath, 'rb') as file:          
      data = file.read(4)                     
      nums = []                               
      while data:                             
          num = struct.unpack("&gt;I", data)[0]  
          print(num)                          
          data = file.read(4)                 
          nums.append(num)                    
  </code></pre>
  
  <p>I am not getting the numbers above (I am for some numbers, but later it gets messed up, probably because of bit padding).</p>
  
  <p>How to stay consistent with bit padding? How can I add something with <code>struct.pack('&gt;I, ...)</code> that I can later reliably get?</p>
  
  <p>Update:</p>
  
  <p>For the following tuple
  <code>[(0, 137), (0, 80), (0, 78), (0, 71), (0, 13), (0, 10), (0, 26), (6, 0), (0, 0), (9, 13), (0, 73), (0, 72), (0, 68), (0, 82), (9, 0), (0, 1), (0, 44), (15, 1), (17, 8), (0, 2), (15, 0), (0, 246) ...]</code></p>
  
  <p>I get the following numbers using my approach:</p>
  
  <p><code>[0, 137, 0, 80, 0, 78, 0, 71, 0, 13, 0, 10, 0, 26, 9, 13, 0, 73, 0, 72, 0, 68, 0, 82, 0, 1, 0, 44, 15, 1, 17, 8, 0, 2, 0, 246 ...]</code></p>
  
  <p>See, at the (6,0) it starts to diverge. Until then it's fine. But it corrects itself?? at  9,13 and continues to do well.</p>