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.

Quetzalcoatl
  • 2,016
  • 4
  • 26
  • 36

2 Answers2

6

use this code:

import binascii
n = int('0110100001101001001000000111010101110011', 2)
binascii.unhexlify('%x' % n)
user 12321
  • 2,846
  • 1
  • 24
  • 34
  • how about much longer strings ? – njzk2 Feb 03 '15 at 21:45
  • @user 12321, perfect! exactly what I need. thank you. will accept your answer asap – Quetzalcoatl Feb 03 '15 at 21:47
  • to my surprise, it does! python apparently does not have much problem with the notion of insanely large integers – njzk2 Feb 03 '15 at 21:47
  • 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. – Quetzalcoatl Feb 03 '15 at 21:49
  • 2
    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. – user 12321 Feb 03 '15 at 21:52
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.

njzk2
  • 38,969
  • 7
  • 69
  • 107