Search code examples
pythonpython-2.7crc16

Calculating CRC16 in Python


I'm trying to evaluate appropriate checksum based on CRC-16 algorithm using crcmod Python module and 2.7 version of Python interpreter. The checksum parameters are:

  • CRC order: 16
  • CRC polynomial: 0x8005
  • Inital value: 0xFFFF
  • Final value: 0x0000
  • Direct: True

Code:

crc16 = crcmod.mkCrcFun(0x18005, rev=False, initCrc=0xFFFF, xorOut=0x0000)
print hex(crc16(str(int(0x5A0001))))

and for the input 0x5A0001 it prints 0x7E16 while I should get something like 0xCE0A.

I checked on http://www.lokker.net/Java/crc/CRCcalculation2.htm and the computed value is 0xACE which is correct (with respect to the order).


Solution

  • crcmod is working fine. You are not giving it the three bytes you think you are giving it. Your str(int(0x5A0001)) is providing seven bytes, which are the ASCII characters 5898241 — the conversion of 0x5a0001 to decimal.

    To feed it the bytes 0x5a 0x00 0x01, you would instead (as one approach):

    print hex(crc16("5a0001".decode("hex")))
    

    That prints 0xace.