Home > Software design >  CRC calculation in chunks
CRC calculation in chunks

Time:12-08

I have a problem when trying to calculate crc in chunks.

This is the code:

unsigned int crc32(const unsigned char *buf, int len, unsigned int init){
  unsigned int crc = init;
  while (len--){
      crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
      buf  ;
    }
  return crc ^ 0xffffffff;
}

int main(){
        unsigned char buf[10]={0,1,2,3,4,5,6,7,8,9};

        printf("crc=x\n",crc32(buf,10,0xffffffff));

        unsigned int crc = crc32(buf,5,0xffffffff);
        printf("crc_chunk1=x\n",crc);
        crc = crc32(buf 5,5,crc);
        printf("crc_chunk1 2=x\n",crc);
}

the first crc call calculate all 10 bytes,

the second calculate the crc of the first 5 bytes

the third calculate the crc of the last 5 bytes but takes the first 5 bytes crc result as a parameter

Output:

crc=9290bbfc
crc_chunk1=06dcaed5 
crc_chunk1 2=d5800060

why crc != crc_chunk1 2?

I want to combine those chunks so the result will be the same.

Thanks.

CodePudding user response:

unsigned int crc32(const unsigned char *buf, int len, unsigned int init)
{
    unsigned int crc = init;
    ...
    return crc ^ 0xffffffff;
}

The function above starts with init, then XORs the result with 0xffffffff

If you are going to feed the result back in to crc32 then you have to XOR once more. The second XOR will undo the transform which was done inside crc32

//one time
unsigned int crc;
crc = crc32(buf, 10, 0xffffffff);
printf("x\n", crc);

//two times
crc = crc32(buf, 5, 0xffffffff);
crc ^= 0xffffffff; //undo previous XOR
crc = crc32(buf   5, 5, crc); //feed back in
printf("x\n", crc);

or change return crc ^ 0xffffffff; to return crc; and XOR it with 0xffffffff before printing.

  • Related