首页 > 解决方案 > 将二进制转换为字符串

问题描述

我需要转换:1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 110 到字符串。我已将字符串转换为二进制

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

现在我无法将其转换回字符串,chr 给了我一些亚洲字符:

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

print(c)
#output:
               

然后我尝试 binascii 但也没有工作:

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"

标签: python-3.xbinary

解决方案


您需要设置basefor int

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

输出:

'This is a string'

推荐阅读