Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRC32 not calculated right

Tags:

c++

crc32

I use a very simple algorithm to calculate the CRC32 but it gives wrong values.

I compare my output values with calculator ones but it always looks different

unsigned int crc32_tab[256] = {
        0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
        0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
        0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
        0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
      .........,..............,.............,.........,...........
    };

Function that use the lookup table is

 unsigned int MyClass::crc32(unsigned int crc, const void *buf, unsigned int   size)
{
const unsigned int *p;

p = (const quint8 *)buf;
crc = crc ^~ 0xFFFFFFFF;

while(size--)
{
    crc = this->crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
}

return crc ^~ 0xFFFFFFFF;
}

I call it by this way

 QString test= QString::number(mclass.crc32(0, crcval, 6))
like image 480
tulipe Avatar asked Mar 01 '26 11:03

tulipe


1 Answers

Solution drawn from chat dicussion

The CRC-32 algorithm being implemented is CRC-32 Ethernet (generator polynomial 0x04C11DB7).

This CRC-32 requires:

  • Being initialized with 0xFFFFFFFF.
  • And being finalized by XORing with 0xFFFFFFFF.

Therefore, you should remove the crc ^~ 0xFFFFFFFF statements within your function, pass 0xFFFFFFFF on your call to the function, and once you're done CRCing the data, you should XOR the return value with 0xFFFFFFFF.

like image 168
Iwillnotexist Idonotexist Avatar answered Mar 03 '26 23:03

Iwillnotexist Idonotexist