简体   繁体   English

如何将字符串的二进制表示形式转换回Python中的原始字符串?

[英]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.

相关问题 如何在python中将二进制字符串转换为双极表示形式? - How to convert a binary string into bipolar representation in python? 如何将 C 二进制缓冲区转换为 Python 字符串中的十六进制表示? - How to convert a C binary buffer to it’s hex representation in Python string? Python:将字符串转换为其二进制表示形式 - Python: Convert a string to its binary representation 如何将二进制字符串的文字字符串表示形式转换为二进制字符串? - How to convert a literal string representation of binary string to a binary string? Python二进制字符串表示形式 - Python binary string representation 如何将文本文件中二进制字符串的字符串表示形式转换回它来自的 utf8 编码文本? - How to convert the string representation of a binary string froma text file back into the utf8 encoded text it came from? 如何将字符串表示形式的字节转换回字节? - how to convert string representation bytes back to bytes? 将二进制字符串转换回二进制(Python 3+) - Convert binary string back to binary (python 3+) 将字节的二进制字符串表示形式转换为 Python 中的实际二进制值 - Convert binary string representation of a byte to actual binary value in Python 将带有转义序列的字符串转换为python中的原始字符表示形式 - Convert a string with escape sequences to their original character representation in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM