Python3如何从整数列表中生成bytes对象

2024-09-27 07:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个整数数组(都小于255),它对应于字节值(即[55, 33, 22]),我如何将其转换为看起来像

b'\x55\x33\x22

谢谢


Tags: 字节整数数组x22x55x33
3条回答

只需调用^{}构造函数。

正如医生所说:

… constructor arguments are interpreted as for bytearray().

如果你遵循这个链接:

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
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构造函数接受一个整数的iterable,因此只需将您的列表馈送给它:

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)

相关问题 更多 >

    热门问题