-4

Using python, I want to convert/interpret a string made of 0 and 1 as if it was binary.

Assume I have a string that looks like this:

>>>str = "010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001"

I would like a function (or whatever) to retrieve Hello World!.

Mikalo
  • 1
  • 1

2 Answers2

3

This should do what you want. for i in xrange(0, len(b), 8) gets the bits for each character separately, and chr(int(b[i:i+8], 2)) converts the ASCII 1s and 0s to the character code.

>>> b = "010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001"
>>> print "".join(chr(int(b[i:i+8], 2)) for i in xrange(0, len(b), 8))
Hello World!
robert
  • 33,242
  • 8
  • 53
  • 74
1
from itertools import izip

str = "010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001"
print ''.join(chr(int(''.join(b8), 2)) for b8 in izip(*[iter(str)]*8))

Output:

Hello World!
Martin Evans
  • 45,791
  • 17
  • 81
  • 97