我需要使用XOR來計算十六進制串行字符串的校驗和。對於我的(有限的)知識,必須使用按位運算符^來執行。此外,數據必須轉換爲二進制整數形式。以下是我的基本代碼 - 但它計算的校驗和是1000831.它應該是01001110或47hex。我認爲這個錯誤可能是由於錯過了前導零。我試圖添加前導零的所有格式都將二進制整數轉換回字符串。我很欣賞任何建議。如何保持二進制整數(python)中的前導零?
word = ('010900004f')
#divide word into 5 separate bytes
wd1 = word[0:2]
wd2 = word[2:4]
wd3 = word[4:6]
wd4 = word[6:8]
wd5 = word[8:10]
#this converts a hex string to a binary string
wd1bs = bin(int(wd1, 16))[2:]
wd2bs = bin(int(wd2, 16))[2:]
wd3bs = bin(int(wd3, 16))[2:]
wd4bs = bin(int(wd4, 16))[2:]
#this converts binary string to binary integer
wd1i = int(wd1bs)
wd2i = int(wd2bs)
wd3i = int(wd3bs)
wd4i = int(wd4bs)
wd5i = int(wd5bs)
#now that I have binary integers, I can use the XOR bitwise operator to cal cksum
checksum = (wd1i^wd2i^wd3i^wd4i^wd5i)
#I should get 47 hex as the checksum
print (checksum, type(checksum))
我想這之前已經得到解決[見這個問題(http://stackoverflow.com/questions/16926130/python-convert-to-binary-and-keep-leading-zeros) – PyNEwbie
0x47!= 0b1001110。很少有奇數以二進制表示的'0'結尾。 – Hyperboreus
@PyNEwbie確實如此,但在這裏我們正面臨一個傑出的XY問題。 – Hyperboreus