我有一个整数数组(全部小于 255)对应于字节值,例如[55、33、22]。我怎样才能把它变成一个看起来像 b'\x55\x33\x22' 的字节对象?
请您参考如下方法:
只需调用 bytes 构造函数。
正如文档所说:
… 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 == b'\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
>>> bytes_of_values
b'U3"'
