所以我得到了以下代码:telegram = "$00;02;A1;00000000*49"checksum = telegram[10:18] # is 00000000for x in telegram[1:]: x = "{0:08b}".format(int(hex(ord(x)),16)) print (x)它输出字符串每个字符的二进制值telegram:0011000000110000001110110011000000110010001110110100000100110001001110110011000000110000001100000011000000110000001100000011000000110000001010100011010000111001现在我想获得电报的校验和,这意味着我必须使用按位运算符^。我确实得到了这样的正确结果:#--snip--firstdigit = "{0:08b}".format(int(hex(ord(telegram[1])),16)) # telegram[1] = 0result_1 = int(firstdigit) ^ int(checksum)print (f'{result_1:08}') # is 00110000seconddigit = "{0:08b}".format(int(hex(ord(telegram[2])),16)) # telegram[2] =0result_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 ...等等。(正确)输出:001100000000000000111011但这样做似乎真的很不方便,这让我遇到了实际问题:我想循环遍历字符串telegram以获得所需的输出,但我就是无法掌握它。如果您能帮助我,我将非常感激!
1 回答
慕码人2483693
TA贡献1860条经验 获得超9个赞
您可以使用每个字符上的函数跳过到二进制字符串的转换ord()。例如:
>>> telegram = "$00;02;A1;00000000*49"
>>> ord(telegram[1]) ^ ord(telegram[2])
0
您可以使用列表理解将所有字符转换为序数:
>>> [ord(n) for n in telegram[1:]] # all but first character...
[48, 48, 59, 48, 50, 59, 65, 49, 59, 48, 48, 48, 48, 48, 48, 48, 48, 42, 52, 57]
使用标准库中的工具(例如functools.reduce和operator.xor),您可以将所有值异或在一起:
>>> import functools
>>> import operator
>>> functools.reduce(operator.xor,[ord(n) for n in telegram[1:]])
110
>>> format(110,'08b') # binary if needed
'01101110'
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消