Create TriggerTest.
[riscv-tests.git] / debug / programs / checksum.c
1 #include <stdint.h>
2
3 // CRC code from http://www.hackersdelight.org/hdcodetxt/crc.c.txt
4
5 // Reverses (reflects) bits in a 32-bit word.
6 unsigned reverse(unsigned x) {
7 x = ((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555);
8 x = ((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333);
9 x = ((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F);
10 x = (x << 24) | ((x & 0xFF00) << 8) |
11 ((x >> 8) & 0xFF00) | (x >> 24);
12 return x;
13 }
14
15 // ----------------------------- crc32a --------------------------------
16
17 /* This is the basic CRC algorithm with no optimizations. It follows the
18 logic circuit as closely as possible. */
19
20 unsigned int crc32a(uint8_t *message, unsigned int size) {
21 int i, j;
22 unsigned int byte, crc;
23
24 i = 0;
25 crc = 0xFFFFFFFF;
26 while (i < size) {
27 byte = message[i]; // Get next byte.
28 byte = reverse(byte); // 32-bit reversal.
29 for (j = 0; j <= 7; j++) { // Do eight times.
30 if ((int)(crc ^ byte) < 0)
31 crc = (crc << 1) ^ 0x04C11DB7;
32 else crc = crc << 1;
33 byte = byte << 1; // Ready next msg bit.
34 }
35 i = i + 1;
36 }
37 return reverse(~crc);
38 }