我需要使用XOR计算十六进制串行字符串的校验和.对于我的(有限的)知识,这必须使用按位运算符^来执行.此外,数据必须转换为二进制整数形式.下面是我的基本代码 - 但它计算的校验和是1000831.它应该是01001110或47hex.我认为错误可能是由于错过了前导零.我试图添加前导零的所有格式都将二进制整数转换回字符串.我很感激任何建议.
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))
Run Code Online (Sandbox Code Playgroud)
为什么要使用所有这些转换和昂贵的字符串函数?
(我将回答XY问题的X部分,而不是Y部分.)
def checksum (s):
v = int (s, 16)
checksum = 0
while v:
checksum ^= v & 0xff
v >>= 8
return checksum
cs = checksum ('010900004f')
print (cs, bin (cs), hex (cs) )
Run Code Online (Sandbox Code Playgroud)
结果是0x47,如预期的那样.顺便说一句0x47是0b1000111而不是如0b1001110所述.