【问题标题】:Convert binary to bytearray with 8bit encoding使用 8 位编码将二进制转换为字节数组
【发布时间】:2017-01-31 06:51:22
【问题描述】:

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

[from_address(1字节)][control_byte(1字节)][标识符(3字节)][长度(3字节)]

数据字段需要格式化为列表或字节数组。我的代码目前执行以下操作:

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

其中dataFormat定义如下:

 def dataFormat(num):
     intermediary = BitArray(bin(num))
     return bytearray(intermediary.bytes)

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

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

我不依赖于上述代码中的任何内容 - 任何获取整数序列并将其转换为字节数组(以字节为单位具有正确大小)的方法将不胜感激。

【问题讨论】:

  • 这需要can标签做什么?
  • @RadLexus 它是罐头信息的一部分。我想与手头的问题没有特别相关。
  • 为什么不使用 CAN 控制器寄存器的消息结构?标识符和长度是 CAN 帧的专用字段,而其他内容必须存储在数据字段中。

标签: python arrays binary can-bus


【解决方案1】:

如果您想要的是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 中也可能有内置的方法来执行此操作,但这不是我经常使用的语言。

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2015-01-21
    • 2021-02-14
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    相关资源
    最近更新 更多