I am writing code which create messages to be sent over a CANBUS using a particular protocol. 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)]
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:
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. 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:
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.