Big Binary Code into File in Python
<p>I have been working on a program and I have been trying to convert a big binary file (As a string) and pack it into a file. I have tried for days to make such thing possible. Here is the code I had written to pack the large binary string. </p>

<pre><code>binaryRecieved="11001010101....(Shortened)"
f=open(fileName,'wb')
m=long(binaryRecieved,2)
struct.pack('i',m)
f.write(struct.pack('i',m))
f.close()
quit()
</code></pre>

<p>I am left with the error</p>

<pre><code>struct.pack('i',x)
struct.error: integer out of range for 'i' format code
</code></pre>

<p>My integer is out of range, so I was wondering if there is a different way of going about with this.</p>

<p>Thanks</p>

<p>For encoding m in big-endian order (like "ten" being written as "10" in normal decimal use) use:</p>

<pre><code>def as_big_endian_bytes(i):
    out=bytearray()
    while i:
        out.append(i&amp;0xff)
        i=i&gt;&gt;8
    out.reverse()
    return out
</code></pre>

<p>For encoding <code>m</code> in little-endian order (like "ten" being written as "01" in normal decimal use) use:</p>

<pre><code>def as_little_endian_bytes(i):
    out=bytearray()
    while i:
        out.append(i&amp;0xff)
        i=i&gt;&gt;8
    return out
</code></pre>

<p>both functions work on numbers - like you do in your question - so the returned bytearray may be shorter than expected (because for numbers leading zeroes do not matter).</p>

<p>For an exact representation of a binary-digit-string (which is only possible if its length is dividable by 8) you would have to do:</p>

<pre><code>def as_bytes(s):
    assert len(s)%8==0
    out=bytearray()
    for i in range(0,len(s)-8,8):
        out.append(int(s[i:i+8],2))
    return out
</code></pre>

python file binary