frozenbooger
frozenbooger

Reputation: 63

Determine 8 bit modulo 256 Checksum form ascii string [-Python]

I want to determine the 8 bit modulo 256 checksum of an ASCII string. I know the formula is:

checksum = (sum of bytes)%256

How can I do this in python (manipulate bytes)? If I start with a string: '1c03e8', I should output 0x94. The main problem is I'm not sure as to how to find the sum of the bytes of an ASCII string. Here is the main idea of what I'm looking for :

https://www.scadacore.com/tools/programming-calculators/online-checksum-calculator/

It has CheckSum8 Modulo 256

I have tried:

component = ('1c03e8') 
for i in range(len(component)):
            checksum.append(int(float(component[i].encode("hex"))))
            print checksum
    print hex(int(sum(checksum)%256))

this although gives me 0x52

Upvotes: 3

Views: 6120

Answers (3)

Muhammad Mohsin
Muhammad Mohsin

Reputation: 91

Try the checksum-calculator package.

Step 1:

pip install checksum-calculator

Step 2:

from checksum_calculator import *


inputString = "your_string"
outputString = inputString.encode('utf-8').hex()


print(compute_checksum8_xor(outputString))
print(compute_checksum8_mod256(outputString))
print(compute_checksum8_2s_complement(outputString))

Upvotes: 1

Marlon Galvão
Marlon Galvão

Reputation: 31

def calc_checksum(s):
    sum = 0
    for c in s:
        sum += ord(c)
    sum = sum % 256
    return '%2X' % (sum & 0xFF)


print calc_checksum('1c03e8'.encode('ascii'))

Upvotes: 3

robobrobro
robobrobro

Reputation: 320

You to need to encode the string as ASCII, because as you said, it's an ASCII string.

Example, quick-and-dirty solution:

print(hex(sum('1c03e8'.encode('ascii')) % 256))

Upvotes: 5

Related Questions