1

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

1
  • I'm guessing you mean m instead of x? In that case long is too much for something that only supports an integer Commented Sep 17, 2016 at 5:23

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

3 Comments

While doubles are (almost) unilimited in how large the numbers may be, they can represent only integers up to 56bit exacly.
+jahbrohl Do you have an alternative?
Yes, see my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.