Pure Python routine for calculation of CRC of arbitrary length

wzab01 at gmail.com wzab01 at gmail.com
Thu Mar 10 03:11:39 EST 2016


Hi,

In my FPGA related work, I had to generate and verify different non-standard CRC sums in a Python based testbench.
I was able to find a few CRC implementations for Python (e.g. crcmod or PyCRC), but none of them was able to work with arbitrary CRC polynomial and data of arbitrary length. Therefore I decided to "reinvent the wheel", and implement something in pure Python from scratch.
The implementation is not aimed on performance, but rather on simplicity.
Therefore, it computes CRC in a loop, not using the table based approach.
The data and the CRC values are represented by the bitarrays (using the bitarray package).

The usage is very simple:

import bitarray
from CRC_ba import CRC

d1=bitarray.bitarray('11010011101110')
d2=bitarray.bitarray('110100101110')

#Calculate the CRC
f=CRC(0b1011,3)
f.update(d1)
f.update(d2)
cr=f.checkCRC() #Without argument, it calculates CRC 
print cr 

#Check the CRC
f=CRC(0b1011,3)
f.update(d1)
f.update(d2)
chk=f.checkCRC(cr)
print chk #We should get zeroes only here

the CRC object constructor accepts the CRC polynomial (as an integer value), the CRC length, and (optionally) the information whether data are transmitted MSB first (the default or 0 value), or LSB first (the 1 value).

The code is not of the highest quality, but it saved me a lot of work, so I published it as PUBLIC DOMAIN in hope that it may be useful for others.
It is available in alt.sources group as "Python routine for CRC of arbitrary length - bitarray based version" or directly at https://groups.google.com/d/msg/alt.sources/dBNqgU1rFYc/A32HmbL9GgAJ

With best regards,
Wojtek



More information about the Python-list mailing list