2017-10-18 56 views
1

我需要計算從銥星模塊(短突發數據)接收到的消息校驗和(以字節爲單位)的最低有效2個字節。Python中的2字節校驗和for銥SBD

我使用的代碼在大多數情況下工作,但它不適用於下面的示例。

我的代碼是:

z=b"AT+SBDRB\r\x00\x18this is a random message\x08\xdb"#message received from Iridium module 
msg=z[11:-2] 
print(msg) 
checksum_received = z[-2:] 
checksum = 0 
check_it = False 

for c in msg: 
    checksum = checksum + C#msg is a byte type 

a=chr(checksum >> 8) 
b=chr(checksum & 0xFF) 
c=a.encode() 
d=b.encode() 
checksum = c + d 

print(c.hex()) 
print(d.hex()) 
print(checksum.hex()) 
print(checksum_received.hex()) 
print(checksum == checksum_received) 

在校驗上述情況不同的是,比我收到的校驗和(我試過多次發送消息,以確保我沒有確實得到一個trasmission錯誤)。

我已經測試所述代碼與下列消息和兩個校驗和是相同的:

z=b"AT+SBDRB\r\x00\x05hello\x02\x14" 
z=b"AT+SBDRB\r\x00\x14thisisarandommessage\x08[" 
z=b"AT+SBDRB\r\x00\x15this isarandommessage\x08{" 

在銥SBDS手冊中給出的唯一信息是:

的校驗和是至少顯著2整個SBD消息的總和的字節數。高位字節必須先發送。例如 如果FA發送ASCII編碼的單詞「hello」給ISU二進制 流將是十六進制68 65 6c 6c 6f 02 14.

回答

0

您似乎將您計算的校驗和轉換爲兩個單獨的chr()值,然後對它們進行編碼。

它更簡單:

z=b"AT+SBDRB\r\x00\x18this is a random message\x08\xdb"#message received from Iridium module 
msg=z[11:-2] 
print(msg) 
checksum_received = z[-2:] 

# checksum = 0 
# for c in msg: 
#  checksum = checksum + C#msg is a byte type 
checksum = sum(msg) 

# checksum is the correct value here 
print(hex(checksum)) 
a = checksum >> 8 
b = checksum & 0xFF 

# Now convert checksum back into a bytes object just like z[-2:] above 
checksum = bytes([a,b]) 
print(checksum.hex()) 
print(checksum_received.hex()) 

# now these two are the same 
print(checksum == checksum_received)