crc-16

Peter Hansen peter at engcorp.com
Thu Jan 29 09:52:13 EST 2004


eugene wrote:
> 
> I looked for a crc-16(crc 16) function to use but couln't find one
> that worked:
> 
> This one is working ..
> 
>         def crc16(s):
[snip]


Since eugene started the thread, I'll continue it by posting one that we've
been using.  It's likely not as fast (eugene's used a lookup table for some
of the work) but it has the added benefit of allowing you to specify which
mask value will be used, so it is more general.  You also have to call it
once for each byte of data rather than wait for all the data to be collected
but sometimes that's more appropriate anyway.

# 16-bit CRCs should detect 65535/65536 or 99.998% of all errors in
# data blocks up to 4096 bytes
MASK_CCITT  = 0x1021     # CRC-CCITT mask (ISO 3309, used in X25, HDLC)
MASK_CRC16  = 0xA001     # CRC16 mask (used in ARC files)

#----------------------------------------------------------------------------
# Calculate and return an incremental CRC value based on the current value
# and the data bytes passed in as a string.
#
def updcrc(crc, data, mask=MASK_CRC16):

    # data_length = len(data)
    # unpackFormat = '%db' % data_length
    # unpackedData = struct.unpack(unpackFormat, data)

    for char in data:
        c = ord(char)
        c = c << 8

        for j in xrange(8):
            if (crc ^ c) & 0x8000:
                crc = (crc << 1) ^ mask
            else:
                crc = crc << 1
            c = c << 1

    return crc & 0xffff


-Peter



More information about the Python-list mailing list