64 lines
1.1 KiB
C
64 lines
1.1 KiB
C
#include <stddef.h>
|
|
#include <stdint.h>
|
|
#include "user.h"
|
|
|
|
uint32_t
|
|
crc32_for_byte(uint32_t r)
|
|
{
|
|
for(int j = 0; j < 8; ++j)
|
|
r = (r & 1 ? 0xEDB88320L ^ (r >> 1) : r >> 1);
|
|
return r;
|
|
}
|
|
|
|
void
|
|
init_crc32_table(uint32_t table[256])
|
|
{
|
|
for(int i = 0; i < 256; ++i)
|
|
table[i] = crc32_for_byte(i);
|
|
}
|
|
|
|
uint32_t
|
|
crc32(uint8_t *data, size_t len, uint32_t crc, uint32_t table[256])
|
|
{
|
|
for(size_t i = 0; i < len; ++i)
|
|
crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
|
|
return crc;
|
|
}
|
|
|
|
int
|
|
main(int argc, char *argv[])
|
|
{
|
|
int fd;
|
|
uint8_t buf[1024];
|
|
size_t n;
|
|
uint32_t crc = 0xFFFFFFFF;
|
|
uint32_t table[256];
|
|
|
|
if(argc != 2) {
|
|
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
|
|
exit(1);
|
|
}
|
|
|
|
if((fd = open(argv[1], 0)) < 0) {
|
|
fprintf(stderr, "Couldnt open: %s\n", argv[1]);
|
|
exit(1);
|
|
}
|
|
|
|
init_crc32_table(table);
|
|
|
|
while((n = read(fd, buf, sizeof(buf))) > 0)
|
|
crc = crc32(buf, n, crc, table);
|
|
|
|
if(n < 0) {
|
|
fprintf(stderr, "Couldnt read file...\n");
|
|
close(fd);
|
|
exit(1);
|
|
}
|
|
|
|
close(fd);
|
|
|
|
crc ^= 0xFFFFFFFF;
|
|
printf("%x\n", crc);
|
|
|
|
return 0;
|
|
}
|