python - 在 Python 3 中将字节转换为可读字符串

标签 python hex byte arrays

我有一个保存数据的 .bin 文件,但我不确定是什么格式或编码。我希望能够将数据转换为可读的内容。格式化不是问题,我可以稍后再做。

我的问题是解析文件。我尝试过使用 struct、binascii 和编解码器,但没有这样的运气。

with open(sys.argv[1], 'rb') as f:
    data = f.read()
    lists = list(data)


    # Below returns that each item is class 'bytes' and a number that appears to be <255
    # However, if I add type(i) == bytes it spits an error
    for i in lists:
        print("Type: ", type(data))
        print(i, "\n")

    # Below returns that the class is 'bytes' and prints like this: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd\x07\x00\x00\x0b\x00\x00\x00\x18\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08@\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0=\xa1D\xc0\x00\x00\x00\x00t\xdfe@
    # To my knowledge, this looks like hex notation. 
    print("Data type: ", type(data))
    print(data)

但是,应该有某种方法可以将其转换为我可以读取的字符,即以字符串表示的字母或数字。我似乎把事情过于复杂化了,因为我确信有一个难以捉摸的内置方法。

最佳答案

使用binascii.hexlify :

>>> import binascii
>>> binascii.hexlify(b'\x00t\xdfe@')
b'0074df6540'

关于python - 在 Python 3 中将字节转换为可读字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541982/

相关文章:

python - LIMIT 0 的查询性能

javascript - 如何将颜色 'Clear'设置为RGB或HEX?

Python - 十进制到整数低字节然后高字节

java - 如何将字符串(表示十六进制值)转换为字节?

python - 最小的 tkSimpleDialog 示例中的错误

python - SUDS 或 SOAPpy : google app engine python

arrays - Delphi-BinToHex 和 HexToBin : Reversal

python - 如何在 python 中通过套接字发送字节?

python - 异步的语义等价物

language-agnostic - 生成颜色列表,从蓝色到红色,从 0% 到 100%