Explain how this algorithm works because I did not find any good, understandable information on this algorithm. Everything is described in mathematical formulas, but I want to understand the very essence of the algorithm. How he works, and in particular, what he does with the incoming data.
1 answer
The crc task is very simple - in accordance with the received bytes, put them in correspondence with 4 bytes (or 2, crc are different). The following conditions are met:
- identical inputs will have the same crc.
- different inputs will have different crc, but may be the same.
- input data that differs quite a bit (a few bits) is likely to have different crc.
The calculation itself is described in Wikipedia and ultimately reduced to mathematical formulas. But if we discard all this, then the bottom line is basically xor and shift. That is, we read data from the input stream, shift / xorim.
Take on wikipedia a very simple crc8 and analyze
/* Name : CRC-8 Poly : 0x31 x^8 + x^5 + x^4 + 1 - Π½Π°Π΄ Π΅Π³ΠΎ Π²ΡΠ±ΠΎΡΠΎΠΌ ΡΠΈΠ΄ΡΡ ΠΌΠ°ΡΠ΅ΠΌΠ°ΡΠΈΠΊΠΈ ΠΈ ΠΊΡΠΈΠΏΡΠΎΠ°Π½Π°Π»ΠΈΡΠΈΠΊΠΈ Init : 0xFF Π½Π°Π΄ ΡΡΠΈΠΌ ΡΠ°ΠΊΠΆΠ΅ Revert: false XorOut: 0x00 Check : 0xF7 ("123456789") ΠΊΠΎΠ½ΡΡΠΎΠ»ΡΠ½ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅, ΡΡΠΎ Π±Ρ ΠΏΡΠΎΠ²Π΅ΡΠΈΡΡ ΡΠ΅Π°Π»ΠΈΠ·Π°ΡΠΈΡ MaxLen: 15 Π±Π°ΠΉΡ(127 Π±ΠΈΡ) - ΠΎΠ±Π½Π°ΡΡΠΆΠ΅Π½ΠΈΠ΅ ΠΎΠ΄ΠΈΠ½Π°ΡΠ½ΡΡ
, Π΄Π²ΠΎΠΉΠ½ΡΡ
, ΡΡΠΎΠΉΠ½ΡΡ
ΠΈ Π²ΡΠ΅Ρ
Π½Π΅ΡΠ΅ΡΠ½ΡΡ
ΠΎΡΠΈΠ±ΠΎΠΊ */ unsigned char Crc8(unsigned char *pcBlock, unsigned int len) { // Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅. ΠΡΠ±ΠΈΡΠ°Π΅ΡΡΡ Ρ ΠΏΠΎΡΠΎΠ»ΠΊΠ° ΠΈΠ»ΠΈ ΡΠΊΡΠΏΠ΅ΡΠΈΠΌΠ΅Π½ΡΠ°Π»ΡΠ½ΠΎ unsigned char crc = 0xFF; unsigned int i; while (len--) // ΠΏΠΎΠΊΠ° Ρ Π½Π°Ρ Π΅ΡΡΡ Π΄Π°Π½Π½ΡΠ΅ { crc ^= *pcBlock++; // ΠΊΡΠΎΡΠΈΠΌ ΠΎΡΠ΅ΡΠ΅Π΄Π½ΠΎΠΉ Π±Π°ΠΉΡ for (i = 0; i < 8; i++) // ΠΏΡΠΈΠΌΠ΅Π½ΡΠ΅ΠΌ ΠΏΠΎΠ»ΠΈΠ½ΠΎΠΌ. ΡΡΡ ΠΏΡΠΎΡΡΠΎ ΠΊΡΠΎΡΠΈΠΌ ΠΈ/ΠΈΠ»ΠΈ ΡΠ΄Π²ΠΈΠ³Π°Π΅ΠΌ. crc = crc & 0x80 ? (crc << 1) ^ 0x31 : crc << 1; } return crc; } In principle, if the polynom is empty, the result is simply sequentially proxied bytes (for crc8) or ints (for crc32).
Wikipedia describes the different values ββof polynomials and initial values ββ(all those magic constants) for various modifications of the algorithm. Which one to choose is a difficult task; here mathematicians let them sit and think. For their applications, the main thing is that the two algorithms have the same algorithm.