Skip to main content
 首页 » 编程设计

python之如何将整数列表转换为字节

2025年05月04日16mfrbuaa

我有一些代表字节的数字,我想从中创建一个 bytes 对象,例如 b"something"

这是我的尝试,为了“做一些研究”的记录。我试图用谷歌搜索它,但只找到了另一个方向(bytes 到数字列表)。我的目标是 b'\x04\x05\x06' 来自 4、5、6。

intelhex 库只是因为那是我需要 bytes 对象的地方。

In [1]: from intelhex import IntelHex 
In [2]: ih = IntelHex() 
In [3]: addr=10 
In [4]: a=5 
In [5]: b=4 
In [6]: c=255 
 
In [7]: ih.puts(addr, bytes(a, b, c)) 
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-7-def738bb7624> in <module>() 
----> 1 ih.puts(addr, bytes(a, b, c)) 
 
TypeError: bytes() argument 2 must be str, not int 
 
In [8]: ih.puts(addr, b'{}{}{}'.format(a, b, c)) 
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
<ipython-input-8-eabba8aef324> in <module>() 
----> 1 ih.puts(addr, b'{}{}{}'.format(a, b, c)) 
 
AttributeError: 'bytes' object has no attribute 'format' 

我可能在这里犯了一些愚蠢的错误,bytes() 函数应该这样做。

请您参考如下方法:

我找到了,确实是愚蠢的错误

我在那里缺少括号。

In [8]: bytes([4,5,6]) 
Out[8]: b'\x04\x05\x06' 

让它帮助 future 的 google 员工。