Write a c program that calculates the crc32 hash of the string "correct horse battery staple" and prints it to stdout. Dont call any builtin crc32 functions.
Write a c program that calculates the crc32 hash of the string "correct horse battery staple" and prints it to stdout. Dont call any builtin crc32 functions.
**CRC32 Hash Calculation in C** ===================================== Below is a simple C program that calculates the CRC32 hash of the string "correct horse battery staple" using the CRC32 algorithm.
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 | #include <stdio.h> // CRC32 polynomial: 0xedb88320 #define CRC32_POLY 0xedb88320 // Function to calculate CRC32 hash unsigned int crc32(const unsigned char* data, unsigned int length) { unsigned int crc = 0xffffffff; for (unsigned int i = 0; i < length; i++) { crc = crc ^ data[i]; for (int j = 0; j < 8; j++) { if (crc & 1) { crc = (crc >> 1) ^ CRC32_POLY; } else { crc = crc >> 1; } } } return ~crc; } int main() { const unsigned char* data = "correct horse battery staple"; unsigned int length = 0; while (data[length] != '\0') { length++; } unsigned int crc = crc32(data, length); printf("CRC32 hash of '%s': 0x%08x\n", data, crc); return 0; } |
1 2 | gcc -o crc32 crc32.c ./crc32 |
I extracted the following code from that output:
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 | #include <stdio.h> // CRC32 polynomial: 0xedb88320 #define CRC32_POLY 0xedb88320 // Function to calculate CRC32 hash unsigned int crc32(const unsigned char* data, unsigned int length) { unsigned int crc = 0xffffffff; for (unsigned int i = 0; i < length; i++) { crc = crc ^ data[i]; for (int j = 0; j < 8; j++) { if (crc & 1) { crc = (crc >> 1) ^ CRC32_POLY; } else { crc = crc >> 1; } } } return ~crc; } int main() { const unsigned char* data = "correct horse battery staple"; unsigned int length = 0; while (data[length] != '\0') { length++; } unsigned int crc = crc32(data, length); printf("CRC32 hash of '%s': 0x%08x\n", data, crc); return 0; } |
Running the following program:
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 | #include <stdio.h> // CRC32 polynomial: 0xedb88320 #define CRC32_POLY 0xedb88320 // Function to calculate CRC32 hash unsigned int crc32(const unsigned char* data, unsigned int length) { unsigned int crc = 0xffffffff; for (unsigned int i = 0; i < length; i++) { crc = crc ^ data[i]; for (int j = 0; j < 8; j++) { if (crc & 1) { crc = (crc >> 1) ^ CRC32_POLY; } else { crc = crc >> 1; } } } return ~crc; } int main() { const unsigned char* data = "correct horse battery staple"; unsigned int length = 0; while (data[length] != '\0') { length++; } unsigned int crc = crc32(data, length); printf("CRC32 hash of '%s': 0x%08x\n", data, crc); return 0; } |
CRC32 hash of 'correct horse battery staple': 0xcb7e6e10
Testing if the previous output contains the string cb7e6e10
: True