0

I used this line of code to turn text into binary and I can't seem to find a way to take the binary from this and turn it back to text. Any help would be greatly appreciated.

' '.join(format(ord(x), 'b') for x in contents)
cs95
  • 379,657
  • 97
  • 704
  • 746
Max
  • 1
  • 4

3 Answers3

2

Works in Python 3.6:

b = ' '.join(format(ord(x), 'b') for x in contents)    
''.join([chr(int(bc, 2)) for bc in b.split(' ')])
Armandas
  • 2,276
  • 1
  • 22
  • 27
2

Not sure what's your problem, works for me:

out = ' '.join(format(ord(x), 'b') for x in "Hello world")
print(out)

1001000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100

If you are asking for how to revert:

revert = ''.join([chr(int(s, 2)) for s in out.split()])
print(revert)

Hello world
Julien
  • 13,986
  • 5
  • 29
  • 53
1

for python 3 this code is working

    binstr = '00100110 00010010'
    s = []
    for i in binstr.split(' '):
        s.append(chr(int(i)))
    print(''.join(s))
         
Sytze
  • 39
  • 1
  • 10