This article demonstrates the implementation of CRC32 algorithm in C language.
CRC32 (Cyclic Redundancy Check) is a widely used checksum algorithm primarily for detecting errors in data transmission or storage. It computes a 32-bit hash value from input data (typically represented as an 8-digit hexadecimal number).
CRC32 Algorithm Implementation in C
This example performs CRC32 calculation on the string "hello world"
:
#include <inttypes.h>
#include <stdio.h>
uint32_t crc32(const char* s){
uint32_t crc = 0xffffffff;
size_t i = 0;
while (s[i] != '\0')
{
uint8_t byte = s[i];
crc = crc ^ byte;
for (uint8_t j = 8; j > 0; --j)
{
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
}
i++;
}
return crc ^ 0xffffffff;
}
int main(){
printf("%" PRIu32 "\n", crc32("hello world"));//222957957
printf("%" PRIx32 "\n", crc32("hello world"));//d4a1185
return 0;
}
Program Output:
222957957 d4a1185