所以我得到了以下代码:
telegram = "$00;02;A1;00000000*49"
checksum = telegram[10:18] # is 00000000
for x in telegram[1:]:
x = "{0:08b}".format(int(hex(ord(x)),16))
print (x)
它输出字符串每个字符的二进制值telegram:
00110000
00110000
00111011
00110000
00110010
00111011
01000001
00110001
00111011
00110000
00110000
00110000
00110000
00110000
00110000
00110000
00110000
00101010
00110100
00111001
现在我想获得电报的校验和,这意味着我必须使用按位运算符^。我确实得到了这样的正确结果:
#--snip--
firstdigit = "{0:08b}".format(int(hex(ord(telegram[1])),16)) # telegram[1] = 0
result_1 = int(firstdigit) ^ int(checksum)
print (f'{result_1:08}') # is 00110000
seconddigit = "{0:08b}".format(int(hex(ord(telegram[2])),16)) # telegram[2] =0
result_2 = int(result_1) ^ int(seconddigit)
print (f'{result_2:08}') # is 00000000
thirddigit = "{0:08b}".format(int(hex(ord(telegram[3])),16)) # telegram[3] =;
result_3 = int(result_2) ^ int(thirddigit)
print (f'{result_3:08}') # is 00111011
...等等。(正确)输出:
00110000
00000000
00111011
但这样做似乎真的很不方便,这让我遇到了实际问题:我想循环遍历字符串telegram以获得所需的输出,但我就是无法掌握它。如果您能帮助我,我将非常感激!
慕码人2483693