Search code examples
pythonpython-3.xhexasciichecksum

calculate checksum hex in Python 3


I want to calculate checksum. The process I want to do like below;

Step-1

a="10F8000041303131303030353000000000000000"

Step-2

10+F8+00+00+41+30+31+31+30+30+30+35+30+00+00+00+00+00+00+00 = D0

Step-3

~D0 = 2F -> 2F + 1 = 30

I tried that;

def calc_checksum_two(s):        
return '%2X' % (-(sum(ord(c) for c in s) % 256) & 0xFF)
print(calc_checksum_two(a))

Result;

3D

Solution

  • b = [a[i:i+2] for i in range(0, len(a), 2)] # ['10', 'F8', '00', ...
    c = [int(i, 16) for i in b] # [16, 248, 0, ...
    d = 256 - sum(c) % 256 # 0x30
    e = hex(d)[2:] # '30'