kiro135
kiro135

Reputation: 53

Crc32 C implementation - doesn't work

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;
}

Upvotes: 5

Views: 744

Answers (1)

Persixty
Persixty

Reputation: 8589

//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;
}

Upvotes: 2

Related Questions