C: the CRC-32 frame check sequence
A cyclic redundancy check (CRC) treats the message as a very long binary number and takes the remainder after division by a fixed polynomial. Link layers such as Ethernet append a CRC-32 to every frame, and the receiver recomputes it. Any single-bit error, and most bursts of errors, change the result.
C
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint32_t crc32(const unsigned char *data, size_t n) {
uint32_t crc = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
crc ^= data[i];
for (int k = 0; k < 8; k++) {
crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
}
}
return ~crc;
}
int main(void) {
unsigned char frame[] = "123456789";
size_t n = strlen((const char *)frame);
printf("crc32 = %08X\n", (unsigned)crc32(frame, n));
frame[3] ^= 0x01;
printf("after one flipped bit = %08X\n", (unsigned)crc32(frame, n));
return 0;
}