CRC64 - Calculate the cyclic redundancy check.

The algorithm to compute the CRC is described in the ISO 3309 standard. The generator polynomial is x64 + x4 + x3 + x + 1. Reference: W. H. Press, S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery, "Numerical recipes in C", 2nd ed., Cambridge University Press. Pages 896ff.


I've not found a CRC64 implementation for python, only a CRC32 from zlib, so I've shamelessly converted a perl one (from SWISS::CRC64, found at http://swissknife.sourceforge.net/CRC64.html). Any improvement/suggestion will be appreciated, as usual. /gp

# Initialisation
# 32 first bits of generator polynomial for CRC64
# the 32 lower bits are assumed to be zero

POLY64REVh = 0xd8000000L
CRCTableh = [0] * 256
CRCTablel = [0] * 256
isInitialized = False

def CRC64(aString):
    global isInitialized
    crcl = 0
    crch = 0
    if (isInitialized is not True):
        isInitialized = True
        for i in xrange(256): 
            partl = i
            parth = 0L
            for j in xrange(8):
                rflag = partl & 1L                
                partl >>= 1L               
                if (parth & 1):
                    partl |= (1L << 31L)
                parth >>= 1L
                if rflag:
	                parth ^= POLY64REVh
            CRCTableh[i] = parth;
            CRCTablel[i] = partl;

    for item in aString:
        shr = 0L
        shr = (crch & 0xFF) << 24
        temp1h = crch >> 8L
        temp1l = (crcl >> 8L) | shr                        
        tableindex = (crcl ^ ord(item)) & 0xFF
        
        crch = temp1h ^ CRCTableh[tableindex]
        crcl = temp1l ^ CRCTablel[tableindex]
    return (crch, crcl)

def CRC64digest(aString):
    return "%08X%08X" % (CRC64(aString))

if __name__ == '__main__':
    assert CRC64("IHATEMATH") == (3822890454, 2600578513)
    assert CRC64digest("IHATEMATH") == "E3DCADD69B01ADD1"
    print 'CRC64: dumb test successful'
      

code.activestate.com ↗