bipster
bipster

Reputation: 474

Python: Get string hex XOR two digit checksum

Newbie here.

I'm trying to get a hex XOR checksum of a string; and I have the following Python 2.7 code:

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')

Now this works fine as a dime EXCEPT for when the result contains 0. If the final value is 02 or 20, it will print only 2. I thought about implementing a .zfill(2), but that would only be applicable for cases where 0 precedes the digit; therefore not reliable.

Any solution to why this might be and how to resolve it?

Upvotes: 0

Views: 1033

Answers (2)

Aritesh
Aritesh

Reputation: 2103

Not the best solution, but works -

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

The issue is that you are removing both "0" and "x" either as leading or trailing. I changed that to sequential lstrip.

You can use regex re as well

Upvotes: 3

TerryA
TerryA

Reputation: 60024

You can use str.format like so:

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

This will format the integer given into hexadecimal while formatting it to display two digits.

For your code, you'd just do return '{:02x}'.format(calc_cksum)

Upvotes: 2

Related Questions