Checksum code

Robin Becker robin at jessikat.fsnet.co.uk
Mon May 27 14:36:41 EDT 2002


I'm having problems with the following contributed code in 2.2, but not
2.1. I suspect that the Python 2.2 changes to int/long in the following
code are causing the problem. Is it true that int overflow is now gone?
If the answer is yes do I do conditional code or is there some neat 2.2
way to do this without ever getting into longs?


        checkSum = calcChecksum(self._data)
        checkSum = _add32(0xB1B0AFBA, -checkSum)


where

def _add32(x, y):
    "Calculate (x + y) modulo 2**32"
    try:
        return x + y
    except OverflowError:
        lo = (x & 0xFFFF) + (y & 0xFFFF)
        hi = (x >> 16) + (y >> 16) + (lo >> 16)
        return (hi << 16) | (lo & 0xFFFF)

def calcChecksum(stream):
    """Calculates PDF-style checksums"""
    if len(stream) & 3:
        stream = stream + "\0\0\0"
        stream = stream[:len(stream)&~3]
    sum = 0
    for n in unpack(">%dl" % (len(stream)/4), stream):
        try:
            sum = sum + n
        except OverflowError:
            # This is just (sum + n) with overflow ignored
            lo = (sum & 0xFFFF) + (n & 0xFFFF)
            hi = (sum >> 16) + (n >> 16) + (lo >> 16)
            sum = (hi << 16) | (lo & 0xFFFF)
    return sum


-- 
Robin Becker



More information about the Python-list mailing list