Reputation: 982
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
Upvotes: 0
Views: 3978
Reputation: 604
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:]
Upvotes: 1
Reputation: 249592
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'
Upvotes: 2