Hi there,
I know there are several posts about this and I browsed and read a lot in the net but I can not find the point where I am mistaken.
I'm doing a transmission from a PC program to an AVR which is using CRC. Don't get me wrong: it is working. I got the code from some example and the other part was done by someone else. But as I'm going to need this on some more platforms and occasions and in possibly more modes, I want to fully understand this. The PC part uses a table based on the 0x1021 polynome it starts like this :
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
and if I'm not mistaken these are the pre-calculated values for each value a byte can have. (Right?) It is widely used and seems correct.
Now on the AVR there is this code :
unsigned int calcrc(char *ptr, int count) { unsigned long int crc; char i; crc = 0; while (--count >= 0) { crc = crc ^ (unsigned int) *ptr++ << 8; i = 8; do { if (crc & 0x8000) crc = crc << 1 ^ 0x1021; else crc = crc << 1; } while(--i); } return (unsigned int)(crc&0x0000FFFF); }
If I now try to verify the values from 0 to 15 everything is ok, but when I try the value for 16 the table says 0x1231 while I'm calculating (manually following the code) 0x0210.
I'm just confused where I'm thinking wrong.
When I have the 16 << 8 it is 0x1000. Now three shifts as there is no 1 on MSB. Then there is the one , so one shift and XORING the 0x1021. Then another 4 shifts as we have the count from 8 to 0. There we are with 0x0210. Or not ?