5

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;
}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
kiro135
  • 53
  • 4
  • Change it back then? – Persixty Apr 28 '15 at 11:44
  • won't work too, I tried it – kiro135 Apr 28 '15 at 11:58
  • Are you sure the polynomial is correct? – fuz Apr 28 '15 at 12:06
  • 3
    @kiro135 Post the original code, as well as some expected inputs and outputs (what it gives and what you expected). If you're trying to implement this: http://www.hackersdelight.org/hdcodetxt/crc.c.txt then I notice that the Hacker's delight code performs the not (~) at the end of the message but above you are applying it for every character `context->crc = ~crc`. – Persixty Apr 28 '15 at 12:10

1 Answers1

2
//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;
}
Persixty
  • 8,165
  • 2
  • 13
  • 35