![](/img/trans.png)
[英]what is the best way to handle variable names in python if the all the variables need to have a float(decimal) in it?
[英]What's the best way to handle multi byte data fields with variable length that also need to have endianness flipped?
我目前正在開發一個程序,該程序通過讀取和寫入 memory 中的地址來與設備交互。 我相信我的串行到 USB 適配器正在交換我發送到設備的字節序,但我不完全確定就是這樣。 我很快就會嘗試另一個,但我仍然很好奇我將如何解決這個問題。
僅此一點對於短的單數據字段命令來說是沒有問題的。 例如:
Source_Address = 0x01
Dest_Address = 0x02
Command_Code = 0x04
Datafield_1 = 0x12345678
在這種情況下,我發送
Source_Address + Dest_Address + Command_Code + reverse byte order Datafield_1
並得到
0x01 0x02 0x04 0x78563412
太好了,但是如果我有很多不同長度的Datafield
子節需要在整個命令中保持它們的順序但它們的字節被顛倒了怎么辦? 例如:
Source_Address = 0x01
Dest_Address = 0x02
Command_Code = 0x05
Datafield_1 = 0x11239041
Datafield_2 = 0x12345876
Datafield_long = 0x1298764536724819
Datafield_longer = 0x783498237859812132125465
...
Datafield_1million = 0x1234567898...
TL;DR變量初始化的順序是它們需要連接的順序,但每個數據字段都需要字節反轉。 數據字段也是可變長度的,有些超過 1000 字節長。 如果它們是統一的,我可以繼續切片和翻轉,但是由於數據字段子部分和長度的數量差異很大,如何以動態方式處理呢?
我懷疑您正在尋找的是 Python結構庫。
我假設較長的數據字段是由重復的結構創建的。
以您的數據,我創建了以下示例:
import struct
import binascii
Source_Address = 0x01
Dest_Address = 0x02
Command_Code = 0x05
Datafields = [0x11239041, 0x12345876]
data_stream = bytearray()
data_stream.extend(struct.pack('<BBB', Source_Address, Dest_Address, Command_Code))
for data in Datafields:
data_stream.extend(struct.pack('<I', data))
# data_stream is packed data in little endian format which you could send.
print(data_stream)
# bytearray(b'\x01\x02\x05A\x90#\x11vX4\x12')
# Hexlify the output for human readability:
print(binascii.hexlify(data_stream))
# b'0102054190231176583412'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.