Quetzalcoatl
Quetzalcoatl

Reputation: 2146

How to convert a binary representation of a string back to the original string in Python?

I haven't been able to find an answer to the following question: Start with a string, convert it to its binary representation. How do you get back the original string in Python?

Example:

a = 'hi us'
b = ''.join(format(ord(c), '08b') for c in a)

then b = 0110100001101001001000000111010101110011

Now I want to get 'hi us' back in Python 2.x. For example, this website accomplishes the task: http://string-functions.com/binary-string.aspx

I've seen several answers for Java, but haven't had luck implementing to Python. I've also tried b.decode(), but don't know which encoding I should use in this case.

Upvotes: 2

Views: 692

Answers (2)

njzk2
njzk2

Reputation: 39406

>>> print ''.join(chr(int(b[i:i+8], 2)) for i in range(0, len(b), 8))
'hi us'

Split b in chunks of 8, parse to int using radix 2, convert to char, join the resulting list as a string.

Upvotes: 2

user 12321
user 12321

Reputation: 2906

use this code:

import binascii
n = int('0110100001101001001000000111010101110011', 2)
binascii.unhexlify('%x' % n)

Upvotes: 6

Related Questions