2

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.

2
  • Check here Commented Feb 3, 2015 at 21:42
  • thank you, but they use 'ascii' to decode, which is not relevant to my question Commented Feb 3, 2015 at 21:42

2 Answers 2

6

use this code:

import binascii
n = int('0110100001101001001000000111010101110011', 2)
binascii.unhexlify('%x' % n)
Sign up to request clarification or add additional context in comments.

5 Comments

how about much longer strings ?
@user 12321, perfect! exactly what I need. thank you. will accept your answer asap
to my surprise, it does! python apparently does not have much problem with the notion of insanely large integers
any further comments on 'efficiency' would be nice. my general question would be: given, say, a string s with len(s) < 25, convert s uniquely to a numerical type, then convert back to get s.
importing binascii will help u and is pretty fast, to make a binarry number out of text use this code: import binascii bin(int(binascii.hexlify('hello'), 16)) and to make it back to string use the answer I posted to your question.
2
>>> 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.

Comments

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.