Created
September 17, 2019 18:44
-
-
Save jwise/d7d31b8e5e2b6d6c904d3e75895dc974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#define POLY 0x04C11DB7 | |
uint32_t crc_table[256]; | |
uint32_t update_crc_slow_1byte(uint32_t crc, uint32_t data) { | |
crc ^= data; | |
for (int i = 0; i < 8; i++) { | |
if (crc & 0x80000000) { | |
crc = (crc << 1) ^ POLY; | |
} else { | |
crc = (crc << 1); | |
} | |
} | |
return crc; | |
} | |
void mk_table() { | |
for (uint32_t i = 0; i < 256; i++) { | |
crc_table[i] = update_crc_slow_1byte(0, i << 24); | |
} | |
} | |
uint32_t update_crc_fast_byte(uint32_t crc, uint8_t data) { | |
uint32_t ent = (crc >> 24) ^ data; | |
return (crc << 8) ^ crc_table[ent]; | |
} | |
uint32_t update_crc(uint32_t crc, uint32_t data) { | |
crc = update_crc_fast_byte(crc, (data >> 24) & 0xFF); | |
crc = update_crc_fast_byte(crc, (data >> 16) & 0xFF); | |
crc = update_crc_fast_byte(crc, (data >> 8) & 0xFF); | |
crc = update_crc_fast_byte(crc, (data ) & 0xFF); | |
return crc; | |
} | |
int main() { | |
uint8_t buf[1024]; | |
size_t len; | |
mk_table(); | |
if (getenv("PRINT_TABLE")) { | |
printf("uint32_t crc_table[] = {"); | |
for (uint32_t i = 0; i < 256; i++) { | |
printf("%s0x%08x, ", (i % 8 == 0) ? "\n\t" : "", crc_table[i]); | |
} | |
printf("\n};\n"); | |
exit(0); | |
} | |
len = read(0, buf, sizeof(buf)); | |
uint32_t crc = 0xffffffff; | |
uint32_t *bufp = (uint32_t *)buf; | |
while (len >= 4) { | |
crc = update_crc(crc, *bufp); | |
bufp++; | |
len -= 4; | |
} | |
/* The last word is kind of funky -- it's little-endian justified, | |
* big-endian. */ | |
if (len > 0) { | |
uint32_t word = 0x0; | |
uint8_t *bufp8 = (uint8_t *)bufp; | |
for (int i = 0; i < len; i++) { | |
word |= bufp8[i] << ((len - i - 1) * 8); | |
} | |
crc = update_crc(crc, word); | |
len -= len; | |
} | |
printf("crc: %08x\n", crc); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment