[英]How to convert a binary representation of a string back to the original string in Python?
I haven't been able to find an answer to the following question: Start with a string, convert it to its binary representation. 我无法找到以下问题的答案:从字符串开始,将其转换为二进制表示形式。 How do you get back the original string in Python?
你如何在Python中找回原始字符串?
Example: 例:
a = 'hi us'
b = ''.join(format(ord(c), '08b') for c in a)
then b = 0110100001101001001000000111010101110011
那么
b = 0110100001101001001000000111010101110011
Now I want to get 'hi us' back in Python 2.x. 现在我想在Python 2.x中回到'hi us'。 For example, this website accomplishes the task: http://string-functions.com/binary-string.aspx
例如,该网站完成了任务: http : //string-functions.com/binary-string.aspx
I've seen several answers for Java, but haven't had luck implementing to Python. 我已经看到了几个Java的答案,但没有运气实现到Python。 I've also tried
b.decode()
, but don't know which encoding I should use in this case. 我也试过
b.decode()
,但不知道在这种情况下我应该使用哪种编码。
use this code: 使用此代码:
import binascii
n = int('0110100001101001001000000111010101110011', 2)
binascii.unhexlify('%x' % n)
>>> print ''.join(chr(int(b[i:i+8], 2)) for i in range(0, len(b), 8))
'hi us'
Split b in chunks of 8, parse to int using radix 2, convert to char, join the resulting list as a string. 将b拆分为8块,使用基数2解析为int,转换为char,将结果列表作为字符串连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.