Computation of a cyclic redundancy check is derived from the mathematics of polynomial division, modulo two. In practice, it resembles long division of the binary message string, with a fixed number of zeroes appended, by the "generator polynomial" string except that exclusive OR operations replace subtractions. Division of this type is efficiently realised in hardware by a modified shift register, and in software by a series of equivalent algorithms, starting with simple code close to the mathematics and becoming faster (and arguably more obfuscated) through byte-wise parallelism and space-time tradeoffs.
Various CRC standards extend the polynomial division algorithm by specifying an initial shift register value, a final exclusive OR step and, most critically, a bit ordering (endianness). As a result, the code seen in practice deviates confusingly from "pure" division, and the register may shift left or right.
Here is a first draft of some pseudocode for computing an n-bit CRC. It uses a contrived composite data type for polynomials, where x
is not an integer variable, but a constructor generating a Polynomial object that can be added, multiplied and exponentiated. To xor
two polynomials is to add them, modulo two; that is, to exclusive OR the coefficients of each matching term from both polynomials.
Note that this example code avoids the need to specify a bit-ordering convention by not using bytes; the input bitString
is already in the form of a bit array, and the remainderPolynomial
is manipulated in terms of polynomial operations; the multiplication by could be a left or right shift, and the addition of bitString[i+n]
is done to the coefficient, which could be the right or left end of the register.