Dan
Dan

Reputation: 344

Big Binary Code into File in Python

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.

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

I am left with the error

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

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

Thanks

Upvotes: 1

Views: 516

Answers (3)

janbrohl
janbrohl

Reputation: 2656

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

def as_big_endian_bytes(i):
    out=bytearray()
    while i:
        out.append(i&0xff)
        i=i>>8
    out.reverse()
    return out

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

def as_little_endian_bytes(i):
    out=bytearray()
    while i:
        out.append(i&0xff)
        i=i>>8
    return out

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).

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:

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

Upvotes: 1

Mehrdad Dadvand
Mehrdad Dadvand

Reputation: 340

In struct.pack you have used 'i' which represents an integer number, which is limited. As your code states, you have a long output; thus, you may want to use 'd' in stead of 'i', to pack your data up as double. It should work.

See Python struct for more information.

Upvotes: 0

James K
James K

Reputation: 3752

Convert your bit string to a byte string: see for example this question Converting bits to bytes in Python. Then pack the bytes with struct.pack('c', bytestring)

Upvotes: 1

Related Questions