0

I have a list that looks like this:

['\x12', '\x13', '\x05', ... , '\xF2'] 

and I'm trying to write it to a file in binary form like this:

00010010
00010011
00000101
11110010

This is what I'm doing now:

for dataLine in readData:
    print int(binascii.hexlify(dataLine), 16)

And then converting to 8 bit binary like so:

def dobin(n):
    digs = []

    while n > 0:
        digs.append(str(n % 2))
        n /= 2

    for x in range(len(digs), 8):
        digs.append('0')

    digs.reverse()
    return ''.join(digs)

Is there an easy way to convert these to binary or a better way all together?

1 Answer 1

1

Here is a version that should work on Python 2.6 (or higher):

>>> data = ['\x12', '\x13', '\x05', '\xF2']
>>> [bin(ord(c))[2:].zfill(8) for c in data]                                                                                                                 
['00010010', '00010011', '00000101', '11110010']

So to write this to a file, I would probably do something like this:

f = open('some_file', 'w')
f.write('\n'.join(bin(ord(c))[2:].zfill(8) for c in data))
f.close()

Edit: Didn't realize that bin() was not available on Python 2.5, you can define the following bin() function to get this to work:

def bin(i):
    s = []
    prefix = '0b' if i >= 0 else '-0b'
    if i < 0: i = -i
    while i:
        s.append('1' if i & 1 else '0')
        i = i >> 1
    return prefix + (''.join(reversed(s)) if s else '0')
Sign up to request clarification or add additional context in comments.

3 Comments

I don't believe bin is available in 2.5 ... I'm getting a name not defined error
As the docs say: "New in version 2.6." But since the OP didn't specify 2.5 as a requirement, it's probably easier to just change the answer, so I'll do that.
I could've swore I mentioned that- my mistake. Thanks for the reply!

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.