Help with CRC calculation

Chris Liechti cliechti at gmx.net
Mon Oct 1 19:21:24 EDT 2001


jwinkelman at movaz.com (Jeff Winkelman) wrote in 
news:90164d1a.0110011213.18fedeb at posting.google.com:

> I am pulling my hair out trying to figure out why my C code calculates
> my CRC correctly, and the Python code does not.  Will some friendly
> person out there please show me the light?
...[cut c code]
> Possible equivalent in Python:
> 
> def crc16(packet):
>     POLY = 0x8048
>     crc = 0xFFFF
> 
>     if len(packet) == 0:
>         return ~crc
> 
> 
>     for byte in packet:
>         data = byte & 0xFF
>         for x in range(8):
>             if ((crc & 0x1) ^ (data & 0x1)):
>                 crc = (crc >> 1) ^ POLY
>             else:
>                 crc = crc >> 1
>             data = data >> 1

in python >= 2.0 "data >>= 1" would also have worked.

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

whats "int" on your system? maybe you need to mask the above number with
"& 0xffff" to keep it within 16 bits. (your c function makes such a cutting 
in the return value, see below.)

>     return -crc

there was no minus operator in the above c example..
and your c function declaration was "unsigned short" that would be 
equivalent when you "return 0xffff & x" in python.

... 
> I saw a posting from Guido that suggested casting the unsigned integer
> into a long and returning it that way (to help with unsigned to signed
> conversion), but it didn't work either.

if your system's "int" is 32 bits and your working with 16 bits unsigned 
there shouldn't be any problem. as python integers are allways signed, 
using 32 bit unsigned numbers in python is most easily done by working with 
longs (that can be as large as you want).

> 
> Any help would be HUGELY appreciated.
> 
> Jeff
> 



-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list