0

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
Purgoufr
  • 761
  • 14
  • 22
  • `sum(ord(c) for c in s)` doesn't look right to me. If s is "10F800", this gives you ord("1") + ord("0") + ord("F") + ord("8") + ord("0") + ord("0"). I don't think that's even close to what you want to be doing. – Kevin Mar 30 '17 at 13:39
  • so how can I sum byte to byte like "10+F8+00+..." – Purgoufr Mar 30 '17 at 13:44

2 Answers2

2
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'
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • e=hex(d) print(e) Result; 0x30 Thank you Jhon :) – Purgoufr Mar 30 '17 at 13:52
  • okay I recently tried to use this function and the checksum I got was incorrect but maybe I misunderstood its usage -- ```ChkSum = hex(sum(c))``` gave me the checksum of the raw values though so basically changed line d -- commenting on this in case someone else stumbles across this and needs just the raw checksum instead of the augmented one – Dennis Jensen Jul 18 '19 at 15:10
1

with s="10F8000041303131303030353000000000000000, sum(ord(c) for c in s) will sum each ord value of each character. This will sums [ord('1'), ord('0'), ord('F'), ...]. This is not what you wanted.

to build array of bytes from that string you should instead using:

[ a[i:i+2]] for i in range(0, len(a), 2) ]

this will create an array like this: ['10', 'F8', '00', ...]

Then to convert string hex/base16 to integer use int(hex_string,16)

That should do it, but here is the function

def calc_checksum_two(a):
    return hex(((sum(int(a[i:i+2],16) for i in range(0, len(a), 2))%0x100)^0xFF)+1)[2:]
izzulmakin
  • 559
  • 1
  • 6
  • 17