简体   繁体   English

使用8位编码将二进制转换为字节数组

[英]Convert binary to bytearray with 8bit encoding

I am writing code which create messages to be sent over a CANBUS using a particular protocol. 我正在编写代码,该代码创建使用特定协议通过CANBUS发送的消息。 An example format for a data field of such a message is: 这种消息的数据字段的格式示例为:

[from_address (1 byte)][control_byte (1 byte)][identifier (3 bytes)][length (3 bytes)] [from_address(1个字节)] [control_byte(1个字节)] [identifier(3个字节)] [length(3个字节)]

The data field needs to be formatted as a list or bytearray. 数据字段需要格式化为列表或字节数组。 My code currently does the following: 我的代码当前执行以下操作:

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

where dataFormat is defined as follows: 其中dataFormat的定义如下:

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

This does exactly what I want it to, except for when from_address is a number that can be described in less than 8 bits. 这完全符合我的要求,除了from_address是一个可以用不到8位描述的数字时。 In these cases bin() returns a binary of character length not divisible by 8 (extraneous zeroes are discarded), and so intermediary.bytes complains that the conversion is ambiguous: 在这些情况下, bin()返回的字符长度的二进制数不能被8整除(丢弃多余的零),因此intermediary.bytes抱怨转换是模棱两可的:

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

I am not tied to anything in the above code - any method to take a sequence of integers and convert it to a bytearray (with correct sizing in terms of bytes) would be greatly appreciated. 我不受上面代码中任何东西的束缚-任何采用整数序列并将其转换为字节数组(具有正确的字节大小)的方法将不胜感激。

If it's a bytearray that you'd like, then the simple option would be to jump straight there and build it up directly. 如果您想要一个bytearray ,那么简单的选择就是直接跳到那里并直接构建它。 Something like this: 像这样:

# 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 . 这是一个可行的例子

Health warning 健康警告

The above assumes that the message is expected to be little endian . 上面假设消息应该是小端的 There may also be built in ways of doing this in Python, but it's not a language I use often. 也可以通过Python来实现此目的,但这不是我经常使用的语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM