二进制到Ascii

时间:2015-04-03 18:34:55

标签: python python-3.x

我想将二进制字符串转换为ASCII。该字符串包含588令牌{0,1}。 我用binascii尝试过它:https://docs.python.org/3/library/binascii.html 或者像这样:Convert binary to ASCII and vice versa

采样代码:

sentence ="0b0101010101..."
n = int(sentence, 2)
print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())

输出:

Error: print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 1: invalid start byte

编辑:现在我的解决方案是优化代码的任何想法吗?

 sentence ="0b0101010101..."
 length=(int(len(sentence)/8)*8)+2
 n = int(sentence[:length:1], 2)
 print (n.to_bytes((n.bit_length() + 7) // 8, 'big').decode("utf_8", "ignore"))

解决!

0 个答案:

没有答案