CRC-32
Compute the CRC-32 used by Ethernet, zip and PNG, bit by bit. A medium embedded C problem (Checksums and CRCs), run and graded in the browser.
medium · Checksums and CRCs · crc · checksum · bits
CRC-32 (as in Ethernet, zip and PNG) is defined by these parameters:
| Width | Poly | Init | RefIn / RefOut | XorOut | Check |
|---|---|---|---|---|---|
| 32 | 0x04C11DB7 | 0xFFFFFFFF | true / true | 0xFFFFFFFF | 0xCBF43926 |
"Reflected" means bits are processed least significant first. The usual way to write it is to shift right and use the bit-reversed polynomial, 0xEDB88320.
Write crc32(data, len). The check value is the CRC of the ASCII string 123456789.
Starter code
uint32_t crc32(const uint8_t *data, size_t len) {
uint32_t crc = 0;
for (size_t i = 0; i < len; i++) {
crc ^= (uint32_t)data[i] << 24;
for (int b = 0; b < 8; b++) crc = (crc & 0x80000000u) ? (crc << 1) ^ 0x04C11DB7u : crc << 1;
}
return crc;
}Example tests
The check value
show("123456789");Expected output:
"123456789": 0xCBF43926Empty input
show("");Expected output:
"": 0x00000000Learn it first
- Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.
More Checksums and CRCs problems
- A table-driven CRC-16 · Build a 256-entry table once, then compute CRC-16/CCITT a byte at a time.
- Load the newest valid settings · Choose between two settings records by magic, CRC and a wrapping sequence number.
- Fix: the receiver rejects some frames · The checksum covers one byte too many.
- Fix: our CRC matches the wrong tool · A CRC-16 routine has the right polynomial and the wrong initial value.
- Greenhouse: trust only good settings · Decide at start-up whether the settings read back from EEPROM can be used.