简体   繁体   English

Python:从二进制转换为String

[英]Python: Converting from binary to String

In Python, I have been able to take in a string of 32 bits, and convert this into a binary number with the following code: 在Python中,我已经能够接收一个32位的字符串,并使用以下代码将其转换为二进制数:

def doConvert(string):
    binary = 0
    for letter in string:
        binary <<= 8
        binary += ord(letter)

    return binary

So for the string, 'abcd' , this method will return the correct value of 1633837924, however I cannot figure out how to do the opposite; 所以对于字符串'abcd' ,这个方法将返回正确的值1633837924,但是我无法弄清楚如何做相反的事情; take in a 32 bit binary number and convert this to a string. 获取32位二进制数并将其转换为字符串。

If someone could help, I would appreciate the help! 如果有人可以提供帮助,我将非常感谢您的帮助!

If you are always dealing with a 32 bit integer you can use the struct module to do this: 如果您始终处理32位整数,则可以使用struct模块执行此操作:

>>> import struct
>>> struct.pack(">I", 1633837924)
'abcd'

Just make sure that you are using the same endianness to both pack and unpack otherwise you will get results that are in the wrong order, for example: 只需确保使用相同的字节顺序来打包和解包,否则您将获得错误顺序的结果,例如:

>>> struct.pack("<I", 1633837924)
'dcba'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM