-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcrc32.c
45 lines (36 loc) · 932 Bytes
/
crc32.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
This is the basic CRC-32 calculation with some optimization but no
table lookup. The the byte reversal is avoided by shifting the crc reg
right instead of left and by using a reversed 32-bit word to represent
the polynomial.
*/
#include <assert.h>
#include <stdint.h>
uint32_t crc32b(uint8_t* message)
{
uint32_t i = 0;
uint32_t crc = 0xFFFFFFFF;
while (message[i] != 0)
{
// Get next byte
uint8_t byte = message[i];
crc = crc ^ byte;
// Do eight times
for (uint32_t j = 0; j < 8; ++j)
{
uint32_t mask = -(crc & 1);
crc = (crc >> 1) ^ (0xEDB88320 & mask);
}
++i;
}
return ~crc;
}
void main()
{
uint32_t r = crc32b("");
assert(r == 0);
uint32_t r2 = crc32b("foobar");
assert(r2 == 2666930069);
uint32_t r3 = crc32b("One day at a time, one step at a time.");
assert(r3 == 237905478);
}