Checksum routine - new to Python

Dale Strickland-Clark dale at out-think.NOSPAMco.uk
Thu May 18 16:25:16 EDT 2000


I need a little checksum routine as part of a larger project. I've written
the one below, which basically works, but it only produces a 32 bit
checksum. I'd prefer a 64 bit checksum but don't know how to code it in
Python. I can't get 'logical and' with >31 bits to work.

This code might look unusual but some of the files I'm checksumming have
long strings of binary zeros at the end which were having the effect of
clearing out the checksum. Also this code will handle files that are all
zeros and still yield a useful result.

If there is a Python library with something suitable, I'll happily use that
instead.

Thanks for any advice/help.

def CheckSum(filepath):

    file = open(filepath, "rb")

    chksum = 0L
    toggle = 0

    allfile = file.read()
    i = 0
    while i < len(allfile):
        ch = allfile[i]
        if ord(ch) > 0:
            if toggle: chksum = chksum << 1
            chksum = chksum + ord(ch)
            chksum = chksum & 0X7fffffff
            toggle = not toggle
        else:
            chksum = chksum + 1
        i = i + 1

    return chksum


--
Dale Strickland-Clark
Out-Think Ltd, UK






More information about the Python-list mailing list