0

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?

bipster
  • 404
  • 1
  • 8
  • 20

2 Answers2

3

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

Aritesh
  • 1,985
  • 1
  • 13
  • 17
2

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)

TerryA
  • 58,805
  • 11
  • 114
  • 143