2017-01-30 45 views
0

我正在編寫創建使用特定協議通過CANBUS發送消息的代碼。這樣的消息的數據字段的示例格式是:使用8位編碼將二進制轉換爲bytearray

[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. 

我不依賴於任何在上面的代碼 - 任何方法來獲取一個整數序列並將其轉換爲一個bytearray(以字節爲單位的正確大小)將不勝感激。

+0

這需要標籤[tag:can]用於什麼? – usr2564301

+0

@RadLexus它是can消息的一部分。我想,這與手邊的問題沒有特別的關係。 – oirectine

+0

爲什麼不使用CAN控制器寄存器的消息結構?標識符和長度是CAN幀的專用字段,而其他的東西必須存儲在數據字段中。 – Lundin

回答

2

如果是你想要的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的方式構建,但它不是我經常使用的語言。

相關問題