# [Tutor] CRC calculation with python

Daniel Yoo dyoo at WPI.EDU
Tue Feb 6 17:25:22 CET 2007

```
On Tue, 6 Feb 2007, Johan Geldenhuys wrote:

> I'm not a C++ expert at all and I would like to find out if somebody can
> explain to me how the statement below can be done in Python?
>
> """
> _uint16 ComCRC16(_uint8 val, _uint16 crc)
> {
>        _uint8 i;
>        _uint16 cval;
>
>    for (i=0;i<8;i++)
>    {
>        if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^
> CCITT_POLY;
>        else   crc >>= 1;
>        val >>= 1;
>    }
>    return crc
> }
>
> """

I agree with Kent that you might want to see if someone has done this work
already.  Still, a translation of the above should be fairly
straightforward.  We do have right shifts, and bitwise operators:

############
>>> (42 >> 1)
21
############

The bit pattern of 42 is shifted to the right by one place: in effect,
doing a division by 2.

We also have XORs and bitwise ANDs:

############
>>> (12345678 ^ 0xdeadbeef)
<stdin>:1: FutureWarning: hex/oct constants > sys.maxint will return
positive values in Python 2.4 and up
-569253983
>>>