0

I have a string of bits I would like to output as a binary file.

s = '10101010'

The string can be much longer or complex than the example above however a shorter one illustrates the point more clearly.

I want to output this so the binary representation of the new file would be 10101010 rather than the string equivalent however I have no idea how best to do this and any help would be appreciated.

Thanks

1
  • 1
    In other words, you want the file to contain a single byte of value 170? Can we assume that the string will always contain a multiple of 8 characters? If not, where should the boundaries between bytes be drawn? Commented Feb 22, 2015 at 16:18

1 Answer 1

2

What you'd want is to split your string to 8-bit-chunks, and then convert them to bytes individually:

for index in range(len(s)/8):
    substring = s[index * 8: index*8 + 8]
    byteval = int(substring, base=2)
    print chr(byteval)
Sign up to request clarification or add additional context in comments.

2 Comments

''.join([chr(int(s[index * 8: index*8 + 8], base=2)) for index in range(len(s)/8)])
@KarolyHorvath: nice list comprehension; definitively faster. My code was a bit on the verbatim side to illustrate the usage of int() for OP.

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.