Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crc32 C implementation - doesn't work

Tags:

c

crc32

I found this CRC32 implementation on the internet, little bit changed it, but I can't get it to work. I initialize it and update it on every byte I get from input, but the hash I get is not what it should be...

typedef struct {
    unsigned short xor;
} xor_context;
void crc32_init(crc32_context *context) {
    context->crc = 0xFFFFFFFF;
}
void crc32_update(crc32_context *context, unsigned char byte) {
    uint32_t crc, mask;

    crc = context->crc;
    crc = crc ^ byte;
    for (int j = 7; j >= 0; j--) {    // Do eight times.
        mask = -(crc & 1);
        crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    context->crc = ~crc;
}

This one is original

unsigned int crc32b(unsigned char *message) {
   int i, j;
   unsigned int byte, crc, mask;

   i = 0;
   crc = 0xFFFFFFFF;
   while (message[i] != 0) {
      byte = message[i];            // Get next byte.
      crc = crc ^ byte;
      for (j = 7; j >= 0; j--) {    // Do eight times.
         mask = -(crc & 1);
         crc = (crc >> 1) ^ (0xEDB88320 & mask);
      }
      i = i + 1;
   }
   return ~crc;
}
like image 308
kiro135 Avatar asked Nov 01 '22 05:11

kiro135


1 Answers

//typedef struct {
//    unsigned short xor;
//} xor_context;//--> Not sure what part this plays in the code!

void crc32_init(crc32_context *context) {
    context->crc = 0xFFFFFFFF;
}

void crc32_update(crc32_context *context, unsigned char byte) {
    uint32_t crc, mask;

    crc = context->crc;
    crc = crc ^ byte;
    for (int j = 7; j >= 0; j--) {    // Do eight times.
        mask = -(crc & 1);
        crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    //context->crc = ~crc; //<-- Don't perform for every byte.
    context->crc = crc; //EDIT: Forgot this!
}

//Completes the check.
uint32_t crc32_complete(crc32_context *context){
    return ~context->crc;
}
like image 189
Persixty Avatar answered Nov 15 '22 07:11

Persixty