Crc32 C实现 - 不起作用

时间:2015-04-28 11:19:16

标签: c crc32

我在互联网上找到了这个CRC32实现,稍微改变了一下,但是我无法让它工作。我初始化它并在我从输入获得的每个字节上更新它,但我得到的哈希不是它应该是...

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

这是原创

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

1 个答案:

答案 0 :(得分: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;
}