Ziggy Witkowski
Ziggy Witkowski

Reputation: 81

Converting binary to string

I need to convert: 1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 1100111 to string. I've converted string to binary

text2 = 'This is a string'
res = ' '.join(format(ord(i), 'b') for i in text2)

print(res)

#output:
1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 1100111

And now I've problem to converting it back to string, chr gives me some asian characters:

c = ' '.join(chr(int(val)) for val in res.split(' '))

print(c)
#output:
󢦴 τŒ³ˆ τŒ³‰ τŽΏ» 𘚠 τŒ³‰ τŽΏ» 𘚠 τŒ£‘ 𘚠 τŽΏ» τ” τŽΏΊ τŒ³‰ τŒ΄Ά τŒ₯

Then I try binascii but also not working:

l = res.split()
print(l)
for i in l:
    print (binascii.b2a_uu(bytes(i, 'utf-8')))
    output:
    b"',3 Q,#$P,   \n"
    b"',3$P,3 P,   \n"
    b"',3$P,3 P,0  \n"
    b"',3$Q,# Q,0  \n"
    b'&,3 P,# P\n'
    b"',3$P,3 P,0  \n"
    b"',3$Q,# Q,0  \n"
    b'&,3 P,# P\n'
    b"',3$P,# P,0  \n"
    b'&,3 P,# P\n'
    b"',3$Q,# Q,0  \n"
    b"',3$Q,#$P,   \n"
    b"',3$Q,# Q,   \n"
    b"',3$P,3 P,0  \n"
    b"',3$P,3$Q,   \n"
    b"',3$P,#$Q,0  \n"

Upvotes: 0

Views: 252

Answers (1)

Chris
Chris

Reputation: 29742

You need to set the base for int:

''.join(chr(int(val, 2)) for val in res.split(' '))

Output:

'This is a string'

Upvotes: 1

Related Questions