簡體   English   中英

Python:獲取字符串十六進制XOR兩位校驗和

[英]Python: Get string hex XOR two digit checksum

新手在這里。

我正在嘗試獲取字符串的十六進制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情況; 因此不可靠。

有什么解決辦法可能會導致這種情況以及如何解決?

您可以這樣使用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

您也可以使用regex re

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM