简体   繁体   English

Python 字节数组打印

[英]Python Bytearray Printing

I have an integer list in Python that should correspond to the following int values (which can be changed to hex byte values):我在 Python 中有一个 integer 列表,它应该对应于以下 int 值(可以更改为十六进制字节值):

[10, 145, 140, 188, 212, 198, 210, 25, 152, 20, 120, 15, 49, 113, 33, 220, 124, 67, 174, 224, 220, 241, 241]

However, when I convert that list to a bytearray (using bytearray(nameOfList)), I get the following printout.但是,当我将该列表转换为 bytearray(使用 bytearray(nameOfList))时,我得到以下打印输出。

bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0\xdc\xf1\xf1')

I can pull the correct values from this byte array, regardless of how it prints, but shouldn't the bytearray printout correspond to the hex values of the byte array?我可以从这个字节数组中提取正确的值,不管它如何打印,但是 bytearray 打印输出不应该对应于字节数组的十六进制值吗? (I mean, it seems to mostly follow the hex values up until after \x0f, where it starts putting out gibberish...) (我的意思是,它似乎主要遵循十六进制值,直到 \x0f 之后,它开始发出乱码......)

>>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0
\xdc\xf1\xf1')
>>> import binascii
>>> print binascii.hexlify(x)
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1

Use binascii if you want all of it to be printed as a hex string如果您希望将所有内容都打印为十六进制字符串,请使用 binascii

It looks fine to me.对我来说看起来不错。 It's just rendering bytes as ASCII characters whenever possible.它只是尽可能将字节呈现为 ASCII 字符。 After 15= \\x0f you have 49='1' and 113='q', etc.在 15= \\x0f你有 49='1' 和 113='q' 等。

See http://asciitable.comhttp://asciitable.com

Use bytes.hex()使用 bytes.hex()

>>> x = bytearray([0x01,0x02,0xff])
>>> print(x.hex())
0102ff

This is probably not very performant at large sizes, but I find this makes it easier to read:这在大尺寸下可能不是很好,但我发现这使它更容易阅读:

buff = bytearray(list(range(10)))
print(buff)
print(", ".join(hex(b) for b in buff))

prints印刷

bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t')
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9

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

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