GNU >> C/C++

crc32


參考資訊:
1. crc32-algorithm-implementation-in-c-without-a-look-up-table-and-with-a-public-li

main.c

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

static char buf[512 * 1024] = {0};

static unsigned int crc32b(unsigned char *buf, int len)
{
   int i = 0, j = 0;
   unsigned int byte = 0, crc = 0, mask = 0;

   crc = 0xffffffff;
   for (i = 0; i < len; i++) {
      byte = buf[i];
      crc = crc ^ byte;
      for (j = 7; j >= 0; j--) {
         mask = -(crc & 1);
         crc = (crc >> 1) ^ (0xedb88320 & mask);
      }
   }
   return ~crc;
}

int main(int argc, char **argv)
{
    int fd = -1, len = 0;
    
    fd = open("test.img", O_RDONLY);
    len = read(fd, buf, sizeof(buf));
    close(fd);

    printf("0x%x\n", crc32b(buf, len));
    return 0;
}


返回上一頁