【问题标题】:Python: Get string hex XOR two digit checksumPython:获取字符串十六进制异或两位校验和
【发布时间】:2018-04-26 18:17:50
【问题描述】:

这里是新手。

我正在尝试获取字符串的十六进制 XOR 校验和;我有以下 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 在数字之前的情况;因此不可靠。

有什么解决方案可以解决为什么会这样以及如何解决它?

【问题讨论】:

    标签: python python-2.7 checksum xor


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      你可以像这样使用str.format

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-14
        • 1970-01-01
        • 2014-01-01
        • 2016-01-23
        • 2019-07-26
        • 2021-12-29
        相关资源
        最近更新 更多