程式語言 - GNU - C/C++ - CRC32



參考資訊:
https://stackoverflow.com/questions/21001659/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;
    int j = 0;
    unsigned int crc = 0;
    unsigned int byte = 0;
    unsigned int mask = 0;

    crc = 0xffffffff;
    for (i = 0; i < len; i++) {
        byte = buf[i];
        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;
    int 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;
}