Python:获取字符串十六进制异或两位校验和

Python: Get string hex XOR two digit checksum

这里是新手。

我正在尝试获取字符串的十六进制异或校验和;我有以下 Python 2.7 代码:

def getCheckSum(sentence):
    calc_cksum = 0
    for s in sentence:
        calc_cksum ^= ord(s)
    return str(hex(calc_cksum)).strip('0x')

print getCheckSum('SOME,1.948.090,SENTENCE,H,ERE')

现在,除了当结果包含 0 时,它可以正常工作。如果最终值为 0220,它将只打印 2。我考虑过实现 .zfill(2),但这只适用于 0 在数字之前的情况;因此不可靠。

关于为什么会这样以及如何解决的任何解决方案?

您可以像这样使用 str.format

>>> '{:02x}'.format(2)
'02'
>>> '{:02x}'.format(123)
'7b'

这会将给定的整数格式化为十六进制,同时将其格式化为显示两位数。

对于您的代码,您只需执行 return '{:02x}'.format(calc_cksum)

不是最好的解决方案,但有效 -

def getCheckSum(sentence):
    calc_cksum = 0
    for s in sentence:
        calc_cksum ^= ord(s)
    return str(hex(calc_cksum)).lstrip("0").lstrip("x")

问题是您要删除前导或尾随的“0”和 "x"。我将其更改为顺序 lstrip.

您也可以使用正则表达式 re