Python3 如何从整数列表创建字节对象

Python3 How to make a bytes object from a list of integers

我有一个整数数组(全部小于 255)对应于字节值(即 [55, 33, 22])我怎样才能把它变成一个看起来像

的字节对象

b'\x55\x33\x22

谢谢

struct.pack("b"*len(my_list),*my_list)

我认为可行

>>> my_list = [55, 33, 22]
>>> struct.pack("b"*len(my_list),*my_list)
b'7!\x16'

如果你想要十六进制,你需要在列表中将其设为十六进制

>>> my_list = [0x55, 0x33, 0x22]
>>> struct.pack("b"*len(my_list),*my_list)
b'U3"'

在所有情况下,如果该值具有 ascii 表示形式,它将在您尝试打印或查看它时显示它...

bytes 构造函数接受整数的可迭代,因此只需将列表提供给它:

l = list(range(0, 256, 23))
print(l)
b = bytes(l)
print(b)

输出:

[0, 23, 46, 69, 92, 115, 138, 161, 184, 207, 230, 253]
b'\x00\x17.E\s\x8a\xa1\xb8\xcf\xe6\xfd'

另请参阅:Python 3 - on converting from ints to 'bytes' and then concatenating them (for serial transmission)

只需调用 bytes 构造函数。

正如文档所说:

… constructor arguments are interpreted as for bytearray().

如果你遵循 link:

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

所以:

>>> list_of_values = [55, 33, 22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values
b'7!\x16'
>>> bytes_of_values == '\x37\x21\x16'
True

当然这些值不会是\x55\x33\x22,因为\x表示十六进制,而十进制值55, 33, 22是十六进制值 37, 21, 16。但是如果你有十六进制值 55, 33, 22,你会得到你想要的输出:

>>> list_of_values = [0x55, 0x33, 0x22]
>>> bytes_of_values = bytes(list_of_values)
>>> bytes_of_values == b'\x55\x33\x22'
True