Python 3 构建字节数组

标签 python python-3.x bytearray

我需要使用原始二进制数据构建一个 tcp 框架,但我发现的所有关于字节的示例和教程都涉及从字符串转换,这不是我需要的。

简而言之,我只需要构建一个字节数组:

0xA2 0x01 0x02 0x03 0x04

请注意,我来自 C/C++ 世界。

我试过了:

frame = b""
frame += bytes( int('0xA2',16) )
frame += bytes( int('0x01',16) )
frame += bytes( int('0x02',16) )
frame += bytes( int('0x03',16) )
frame += bytes( int('0x04',16) )

然后,将此帧变量扔给套接字的发送方法,但由于帧不包含我想要的内容而无法按预期工作...

我知道这是一个关于 Python 的非常基本的问题,所以如果你能指出我正确的方向......

最佳答案

使用 bytearray :

>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')

或者,使用您的代码但修复错误:

frame = b""
frame += b'\xA2' 
frame += b'\x01' 
frame += b'\x02' 
frame += b'\x03'
frame += b'\x04'

关于Python 3 构建字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555689/

相关文章:

字节数组的十六进制表示

python - 我的属性 setter 有问题

python - 从 django/python 中的日志文件读取后如何保持数据格式化

python - Django 检查单个字段是否有错误并且不运行 clean()?

python - python < 2.7 的 unittest setUpClass 替代方案

python - 如何将包含多个字典的列表转换为字典

python-3.x - np.where的不同类型的结果。x,y在两个条件下互换。我想念什么?

python-3.x - 为什么 statsmodels.api 生成的 R^2 为 1.000?

java - com.google.gson.JsonSyntaxException : Expected BEGIN_ARRAY but was STRING

java - 如何在java中合并2个二进制字节数组