| 1 |
|
| 2 |
#include <sys/types.h> |
| 3 |
#include <stdlib.h> |
| 4 |
#include <stdint.h> |
| 5 |
|
| 6 |
static uint32_t crc32_reverse(uint32_t x) |
| 7 |
{ |
| 8 |
x = ((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555); |
| 9 |
x = ((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333); |
| 10 |
x = ((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F); |
| 11 |
x = (x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24); |
| 12 |
return x; |
| 13 |
} |
| 14 |
|
| 15 |
uint32_t crc32(uint32_t iv, uint32_t sv, const void *data, size_t n) |
| 16 |
{ |
| 17 |
const unsigned char *ptr; |
| 18 |
unsigned x; |
| 19 |
uint32_t byte, crc; |
| 20 |
|
| 21 |
crc = iv; |
| 22 |
ptr = data; |
| 23 |
while (n--) { |
| 24 |
byte = *ptr++; |
| 25 |
byte = crc32_reverse(byte); |
| 26 |
for (x = 0; x < 8; x++, byte <<= 1) crc = ((crc ^ byte) & 0x80000000U) ? (crc << 1) ^ sv : (crc << 1); |
| 27 |
} |
| 28 |
|
| 29 |
return crc; |
| 30 |
} |
| 31 |
|
| 32 |
uint32_t crc32_final(uint32_t iv) |
| 33 |
{ |
| 34 |
return crc32_reverse(iv ^ ~0U); |
| 35 |
} |