2024-09-27 07:21:59 发布
网友
我有一个整数数组(都小于255),它对应于字节值(即[55, 33, 22]),我如何将其转换为看起来像
[55, 33, 22]
b'\x55\x33\x22等
b'\x55\x33\x22
谢谢
只需调用^{}构造函数。
正如医生所说:
… constructor arguments are interpreted as for bytearray().
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.
0 <= x < 256
所以:
>>> 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,你会得到你想要的输出:
\x55\x33\x22
\x
55, 33, 22
37, 21, 16
>>> 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,因此只需将您的列表馈送给它:
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)
只需调用^{} 构造函数。
正如医生所说:
如果你遵循这个链接:
所以:
当然,这些值不会是
\x55\x33\x22
,因为\x
表示十六进制,而十进制值55, 33, 22
是十六进制值37, 21, 16
。但是如果你有十六进制值55, 33, 22
,你会得到你想要的输出:我想会有用的
如果你想要十六进制,你需要把它列在列表中
在所有情况下,如果该值有一个ascii表示,当您试图打印或查看它时,它将显示它。。。
bytes
构造函数接受一个整数的iterable,因此只需将您的列表馈送给它:输出:
另请参见:Python 3 - on converting from ints to 'bytes' and then concatenating them (for serial transmission)
相关问题 更多 >
编程相关推荐