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)
4
  • Can you show your input, and desired output? Commented Jan 12, 2018 at 4:28
  • Hello world 1001000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100 Commented Jan 12, 2018 at 4:29
  • stackoverflow.com/questions/7396849/… Commented Jan 12, 2018 at 4:31
  • Then, Id like to be able to take the output and convert it back to the input. Commented Jan 12, 2018 at 4:31

3 Answers 3

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(' ')])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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))
         

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.