title: How to encode a long in Base64 in Python?
body: <p>In Java, I can encode a <code>BigInteger</code> as:</p>
  
  <pre><code>java.math.BigInteger bi = new java.math.BigInteger("65537L");
  String encoded = Base64.encodeBytes(bi.toByteArray(), Base64.ENCODE|Base64.DONT_GUNZIP);
  
  // result: 65537L encodes as "AQAB" in Base64
  
  byte[] decoded = Base64.decode(encoded, Base64.DECODE|Base64.DONT_GUNZIP);
  java.math.BigInteger back = new java.math.BigInteger(decoded);
  </code></pre>
  
  <p>In C#:</p>
  
  <pre><code>System.Numerics.BigInteger bi = new System.Numerics.BigInteger("65537L");
  string encoded = Convert.ToBase64(bi);
  byte[] decoded = Convert.FromBase64String(encoded);
  System.Numerics.BigInteger back = new System.Numerics.BigInteger(decoded);
  </code></pre>
  
  <p>How can I encode long integers in Python as Base64-encoded strings? What I've tried so far produces results different from implementations in other languages (so far I've tried in Java and C#), particularly it produces longer-length Base64-encoded strings.</p>
  
  <pre><code>import struct
  encoded = struct.pack('I', (1&lt;&lt;16)+1).encode('base64')[:-1]
  # produces a longer string, 'AQABAA==' instead of the expected 'AQAB'
  </code></pre>
  
  <p>When using this Python code to produce a Base64-encoded string, the resulting decoded integer in Java (for example) produces instead <code>16777472</code> in place of the expected <code>65537</code>. Firstly, what am I missing?</p>
  
  <p>Secondly, I have to figure out by hand what is the length format to use in <code>struct.pack</code>; and if I'm trying to encode a long number (greater than <code>(1&lt;&lt;64)-1</code>) the <code>'Q'</code> format specification is too short to hold the representation. Does that mean that I have to do the representation by hand, or is there an undocumented format specifier for the <code>struct.pack</code> function? (I'm not compelled to use <code>struct</code>, but at first glance it seemed to do what I needed.)</p>