How to get a CCITT-CRC16 on Python's crcmod lybrary?

SnowBG picture SnowBG · Jun 16, 2014 · Viewed 8k times · Source

I'm having problems to make a code in Python 3.4 using the CRCMOD library to get the CCITT CRC16 check.

Thats my string:

a731986b1500087f9206e82e3829fe8bcffed5555efd00a100980000010000000100000009010013bb1d001e287107009b3000000300000088330000f427500077026309

The spected crc value is 1d7f

My code:

import crcmod

crc16 = crcmod.mkCrcFun(0x11021, 0x1d0f, False, 0x0000)

hex(crc16(b'a731986b1500087f9206e82e3829fe8bcffed5555efd00a100980000010000000100000009010013bb1d001e287107009b3000000300000088330000f427500077026309'))

It returns: 7d67

What am I doing wrong?

Answer

mhawke picture mhawke · Jun 16, 2014

You first need to convert the data from its hex representation to binary. You also need to use the correct CRC algorithm, which I think is "xmodem" - crcmod.mkCrcFun(0x11021, 0x0000, False, 0x0000)

import crcmod.predefined
from binascii import unhexlify

s = unhexlify('a731986b1500087f9206e82e3829fe8bcffed5555efd00a100980000010000000100000009010013bb1d001e287107009b3000000300000088330000f427500077026309')

crc16 = crcmod.predefined.Crc('xmodem')
crc16.update(s)
print crc16.hexdigest()

Outputs 7F1D (which is what you expected but with the bytes reversed)