使用8位编码将二进制转换为bytearray

2024-06-01 09:59:11 发布

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

我正在编写代码,创建消息,以便使用特定的协议通过CANBUS发送。此类消息的数据字段的格式示例如下:

[起始地址(1字节)][控制字节(1字节)][标识符(3字节)][长度(3字节)]

数据字段需要格式化为list或bytearray。我的代码当前执行以下操作:

 data = dataFormat((from_address << 56)|(control_byte << 48)|(identifier << 24)|(length))

其中dataFormat定义如下:

^{pr2}$

这完全符合我的要求,除了from_address是一个可以用不到8位来描述的数字。在这些情况下,bin()返回一个字符长度不可被8整除的二进制(多余的零被丢弃),因此intermediary.bytes抱怨转换不明确:

 InterpretError: Cannot interpret as bytes unambiguously - not multiple of 8 bits.

我不受上面代码中的任何东西的约束-任何获取整数序列并将其转换为bytearray的方法(以字节为单位进行正确的大小调整)将是非常感谢的。在


Tags: 代码from消息协议示例字节bytesaddress
1条回答
网友
1楼 · 发布于 2024-06-01 09:59:11

如果您想要一个bytearray,那么简单的选择就是直接跳到那里并直接构建它。像这样:

# Define some values:
from_address = 14
control_byte = 10
identifier = 80
length = 109

# Create a bytearray with 8 spaces:
message = bytearray(8)

# Add from and control:
message[0] = from_address
message[1] = control_byte

# Little endian dropping in of the identifier:
message[2] = identifier & 255
message[3] = (identifier >> 8) & 255
message[4] = (identifier >> 16) & 255

# Little endian dropping in of the length:
message[5] = length & 255
message[6] = (length >> 8) & 255
message[7] = (length >> 16) & 255

# Display bytes:
for value in message:
    print(value)

Here's a working example of that。在

健康警告

上面假设消息应该是little endian。在Python中也可能有很多方法可以实现这一点,但我并不经常使用这种语言。在

相关问题 更多 >