Help with CRC calculation

Peter Hansen peter at engcorp.com
Tue Oct 2 01:14:18 CEST 2001


Jeff Winkelman wrote:
> 
> CRC Algorithm in C:
> 
> unsigned short CRC16(char *pData, unsigned short length)
> {
>       unsigned char i;
>       unsigned int data;
>       unsigned int crc = 0xffff;

What size are your ints?  I'm guessing they're really 16-bit
ints, rather than 32.

>       crc = ~crc;
>       data = crc;
>       crc = (crc << 8) | ((data >> 8) & 0xff);

Without looking at past code I've used I can't be sure,
but it looks like that code (all of what you posted)
depends on a 16-bit integer.

> Possible equivalent in Python:
> 
> def crc16(packet):
>     POLY = 0x8048
>     crc = 0xFFFF
> 
>     if len(packet) == 0:
>         return ~crc

In Python, this returns 0xFFFF0000 for example.  Probably
not what you want and not what C does with 16-bit ints.

>     crc = ~crc
>     data = crc
>     crc = (crc << 8) | ((data >> 8) & 0xFF)
>     return -crc

Chances are both the ~crc and the (crc << 8) need to have an
"and 0xffff" added after them to perform the effect of C's 
automatic truncation of results to the 16-bit size.

Or it could be something else. :-)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list