Python Bytearray 打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17093700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:25:25  来源:igfitidea点击:

Python Bytearray Printing

pythonpython-3.x

提问by panoptical

I have an integer list in Python that should correspond to the following int values (which can be changed to hex byte values):

我在 Python 中有一个整数列表,它应该对应于以下 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(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? (I mean, it seems to mostly follow the hex values up until after \x0f, where it starts putting out gibberish...)

我可以从这个字节数组中提取正确的值,不管它是如何打印的,但是字节数组的打印输出不应该对应于字节数组的十六进制值吗?(我的意思是,它似乎主要遵循十六进制值,直到 \x0f 之后,它开始发出胡言乱语......)

采纳答案by Lelouch Lamperouge

>>> 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

回答by axblount

It looks fine to me. It's just rendering bytes as ASCII characters whenever possible. After 15=\x0fyou have 49='1' and 113='q', etc.

对我来说看起来不错。它只是尽可能将字节呈现为 ASCII 字符。在 15= 之后,\x0f你有 49='1' 和 113='q',等等。

See http://asciitable.com

http://asciitable.com