home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / CRC.TXT < prev    next >
Text File  |  1997-07-05  |  91KB  |  2,084 lines

  1. +++Date last modified: 05-Jul-1997
  2.  
  3. =============================================================================
  4. A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS
  5. ==================================================
  6. "Everything you wanted to know about CRC algorithms, but were afraid
  7. to ask for fear that errors in your understanding might be detected."
  8.  
  9. Version : 3.
  10. Date    : 19 August 1993.
  11. Author  : Ross N. Williams.
  12. Net     : ross@guest.adelaide.edu.au.
  13. FTP     : ftp.adelaide.edu.au/pub/rocksoft/crc_v3.txt
  14. Company : Rocksoft^tm Pty Ltd.
  15. Snail   : 16 Lerwick Avenue, Hazelwood Park 5066, Australia.
  16. Fax     : +61 8 373-4911 (c/- Internode Systems Pty Ltd).
  17. Phone   : +61 8 379-9217 (10am to 10pm Adelaide Australia time).
  18. Note    : "Rocksoft" is a trademark of Rocksoft Pty Ltd, Australia.
  19. Status  : Copyright (C) Ross Williams, 1993. However, permission is
  20.           granted to make and distribute verbatim copies of this
  21.           document provided that this information block and copyright
  22.           notice is included. Also, the C code modules included
  23.           in this document are fully public domain.
  24. Thanks  : Thanks to Jean-loup Gailly (jloup@chorus.fr) and Mark Adler
  25.           (me@quest.jpl.nasa.gov) who both proof read this document
  26.           and picked out lots of nits as well as some big fat bugs.
  27.  
  28. Table of Contents
  29. -----------------
  30.     Abstract
  31.  1. Introduction: Error Detection
  32.  2. The Need For Complexity
  33.  3. The Basic Idea Behind CRC Algorithms
  34.  4. Polynomial Arithmetic
  35.  5. Binary Arithmetic with No Carries
  36.  6. A Fully Worked Example
  37.  7. Choosing A Poly
  38.  8. A Straightforward CRC Implementation
  39.  9. A Table-Driven Implementation
  40. 10. A Slightly Mangled Table-Driven Implementation
  41. 11. "Reflected" Table-Driven Implementations
  42. 12. "Reversed" Polys
  43. 13. Initial and Final Values
  44. 14. Defining Algorithms Absolutely
  45. 15. A Parameterized Model For CRC Algorithms
  46. 16. A Catalog of Parameter Sets for Standards
  47. 17. An Implementation of the Model Algorithm
  48. 18. Roll Your Own Table-Driven Implementation
  49. 19. Generating A Lookup Table
  50. 20. Summary
  51. 21. Corrections
  52.  A. Glossary
  53.  B. References
  54.  C. References I Have Detected But Haven't Yet Sighted
  55.  
  56.  
  57. Abstract
  58. --------
  59. This document explains CRCs (Cyclic Redundancy Codes) and their
  60. table-driven implementations in full, precise detail. Much of the
  61. literature on CRCs, and in particular on their table-driven
  62. implementations, is a little obscure (or at least seems so to me).
  63. This document is an attempt to provide a clear and simple no-nonsense
  64. explanation of CRCs and to absolutely nail down every detail of the
  65. operation of their high-speed implementations. In addition to this,
  66. this document presents a parameterized model CRC algorithm called the
  67. "Rocksoft^tm Model CRC Algorithm". The model algorithm can be
  68. parameterized to behave like most of the CRC implementations around,
  69. and so acts as a good reference for describing particular algorithms.
  70. A low-speed implementation of the model CRC algorithm is provided in
  71. the C programming language. Lastly there is a section giving two forms
  72. of high-speed table driven implementations, and providing a program
  73. that generates CRC lookup tables.
  74.  
  75.  
  76. 1. Introduction: Error Detection
  77. --------------------------------
  78. The aim of an error detection technique is to enable the receiver of a
  79. message transmitted through a noisy (error-introducing) channel to
  80. determine whether the message has been corrupted. To do this, the
  81. transmitter constructs a value (called a checksum) that is a function
  82. of the message, and appends it to the message. The receiver can then
  83. use the same function to calculate the checksum of the received
  84. message and compare it with the appended checksum to see if the
  85. message was correctly received. For example, if we chose a checksum
  86. function which was simply the sum of the bytes in the message mod 256
  87. (i.e. modulo 256), then it might go something as follows. All numbers
  88. are in decimal.
  89.  
  90.    Message                    :  6 23  4
  91.    Message with checksum      :  6 23  4 33
  92.    Message after transmission :  6 27  4 33
  93.  
  94. In the above, the second byte of the message was corrupted from 23 to
  95. 27 by the communications channel. However, the receiver can detect
  96. this by comparing the transmitted checksum (33) with the computer
  97. checksum of 37 (6 + 27 + 4). If the checksum itself is corrupted, a
  98. correctly transmitted message might be incorrectly identified as a
  99. corrupted one. However, this is a safe-side failure. A dangerous-side
  100. failure occurs where the message and/or checksum is corrupted in a
  101. manner that results in a transmission that is internally consistent.
  102. Unfortunately, this possibility is completely unavoidable and the best
  103. that can be done is to minimize its probability by increasing the
  104. amount of information in the checksum (e.g. widening the checksum from
  105. one byte to two bytes).
  106.  
  107. Other error detection techniques exist that involve performing complex
  108. transformations on the message to inject it with redundant
  109. information. However, this document addresses only CRC algorithms,
  110. which fall into the class of error detection algorithms that leave the
  111. data intact and append a checksum on the end. i.e.:
  112.  
  113.       <original intact message> <checksum>
  114.  
  115.  
  116. 2. The Need For Complexity
  117. --------------------------
  118. In the checksum example in the previous section, we saw how a
  119. corrupted message was detected using a checksum algorithm that simply
  120. sums the bytes in the message mod 256:
  121.  
  122.    Message                    :  6 23  4
  123.    Message with checksum      :  6 23  4 33
  124.    Message after transmission :  6 27  4 33
  125.  
  126. A problem with this algorithm is that it is too simple. If a number of
  127. random corruptions occur, there is a 1 in 256 chance that they will
  128. not be detected. For example:
  129.  
  130.    Message                    :  6 23  4
  131.    Message with checksum      :  6 23  4 33
  132.    Message after transmission :  8 20  5 33
  133.  
  134. To strengthen the checksum, we could change from an 8-bit register to
  135. a 16-bit register (i.e. sum the bytes mod 65536 instead of mod 256) so
  136. as to apparently reduce the probability of failure from 1/256 to
  137. 1/65536. While basically a good idea, it fails in this case because
  138. the formula used is not sufficiently "random"; with a simple summing
  139. formula, each incoming byte affects roughly only one byte of the
  140. summing register no matter how wide it is. For example, in the second
  141. example above, the summing register could be a Megabyte wide, and the
  142. error would still go undetected. This problem can only be solved by
  143. replacing the simple summing formula with a more sophisticated formula
  144. that causes each incoming byte to have an effect on the entire
  145. checksum register.
  146.  
  147. Thus, we see that at least two aspects are required to form a strong
  148. checksum function:
  149.  
  150.    WIDTH: A register width wide enough to provide a low a-priori
  151.           probability of failure (e.g. 32-bits gives a 1/2^32 chance
  152.           of failure).
  153.  
  154.    CHAOS: A formula that gives each input byte the potential to change
  155.           any number of bits in the register.
  156.  
  157. Note: The term "checksum" was presumably used to describe early
  158. summing formulas, but has now taken on a more general meaning
  159. encompassing more sophisticated algorithms such as the CRC ones. The
  160. CRC algorithms to be described satisfy the second condition very well,
  161. and can be configured to operate with a variety of checksum widths.
  162.  
  163.  
  164. 3. The Basic Idea Behind CRC Algorithms
  165. ---------------------------------------
  166. Where might we go in our search for a more complex function than
  167. summing? All sorts of schemes spring to mind. We could construct
  168. tables using the digits of pi, or hash each incoming byte with all the
  169. bytes in the register. We could even keep a large telephone book
  170. on-line, and use each incoming byte combined with the register bytes
  171. to index a new phone number which would be the next register value.
  172. The possibilities are limitless.
  173.  
  174. However, we do not need to go so far; the next arithmetic step
  175. suffices. While addition is clearly not strong enough to form an
  176. effective checksum, it turns out that division is, so long as the
  177. divisor is about as wide as the checksum register.
  178.  
  179. The basic idea of CRC algorithms is simply to treat the message as an
  180. enormous binary number, to divide it by another fixed binary number,
  181. and to make the remainder from this division the checksum. Upon
  182. receipt of the message, the receiver can perform the same division and
  183. compare the remainder with the "checksum" (transmitted remainder).
  184.  
  185. Example: Suppose the message consisted of the two bytes (6,23) as
  186. in the previous example. These can be considered to be the hexadecimal
  187. number 0617 which can be considered to be the binary number
  188. 0000-0110-0001-0111. Suppose that we use a checksum register one-byte
  189. wide and use a constant divisor of 1001, then the checksum is the
  190. remainder after 0000-0110-0001-0111 is divided by 1001. While in this
  191. case, this calculation could obviously be performed using common
  192. garden variety 32-bit registers, in the general case this is messy. So
  193. instead, we'll do the division using good-'ol long division which you
  194. learnt in school (remember?). Except this time, it's in binary:
  195.  
  196.           ...0000010101101 = 00AD =  173 = QUOTIENT
  197.          ____-___-___-___-
  198. 9= 1001 ) 0000011000010111 = 0617 = 1559 = DIVIDEND
  199. DIVISOR   0000.,,....,.,,,
  200.           ----.,,....,.,,,
  201.            0000,,....,.,,,
  202.            0000,,....,.,,,
  203.            ----,,....,.,,,
  204.             0001,....,.,,,
  205.             0000,....,.,,,
  206.             ----,....,.,,,
  207.              0011....,.,,,
  208.              0000....,.,,,
  209.              ----....,.,,,
  210.               0110...,.,,,
  211.               0000...,.,,,
  212.               ----...,.,,,
  213.                1100..,.,,,
  214.                1001..,.,,,
  215.                ====..,.,,,
  216.                 0110.,.,,,
  217.                 0000.,.,,,
  218.                 ----.,.,,,
  219.                  1100,.,,,
  220.                  1001,.,,,
  221.                  ====,.,,,
  222.                   0111.,,,
  223.                   0000.,,,
  224.                   ----.,,,
  225.                    1110,,,
  226.                    1001,,,
  227.                    ====,,,
  228.                     1011,,
  229.                     1001,,
  230.                     ====,,
  231.                      0101,
  232.                      0000,
  233.                      ----
  234.                       1011
  235.                       1001
  236.                       ====
  237.                       0010 = 02 = 2 = REMAINDER
  238.  
  239.  
  240. In decimal this is "1559 divided by 9 is 173 with a remainder of 2".
  241.  
  242. Although the effect of each bit of the input message on the quotient
  243. is not all that significant, the 4-bit remainder gets kicked about
  244. quite a lot during the calculation, and if more bytes were added to
  245. the message (dividend) it's value could change radically again very
  246. quickly. This is why division works where addition doesn't.
  247.  
  248. In case you're wondering, using this 4-bit checksum the transmitted
  249. message would look like this (in hexadecimal): 06172 (where the 0617
  250. is the message and the 2 is the checksum). The receiver would divide
  251. 0617 by 9 and see whether the remainder was 2.
  252.  
  253.  
  254. 4. Polynomial Arithmetic
  255. -------------------------
  256. While the division scheme described in the previous section is very
  257. very similar to the checksumming schemes called CRC schemes, the CRC
  258. schemes are in fact a bit weirder, and we need to delve into some
  259. strange number systems to understand them.
  260.  
  261. The word you will hear all the time when dealing with CRC algorithms
  262. is the word "polynomial". A given CRC algorithm will be said to be
  263. using a particular polynomial, and CRC algorithms in general are said
  264. to be operating using polynomial arithmetic. What does this mean?
  265.  
  266. Instead of the divisor, dividend (message), quotient, and remainder
  267. (as described in the previous section) being viewed as positive
  268. integers, they are viewed as polynomials with binary coefficients.
  269. This is done by treating each number as a bit-string whose bits are
  270. the coefficients of a polynomial. For example, the ordinary number 23
  271. (decimal) is 17 (hex) and 10111 binary and so it corresponds to the
  272. polynomial:
  273.  
  274.    1*x^4 + 0*x^3 + 1*x^2 + 1*x^1 + 1*x^0
  275.  
  276. or, more simply:
  277.  
  278.    x^4 + x^2 + x^1 + x^0
  279.  
  280. Using this technique, the message, and the divisor can be represented
  281. as polynomials and we can do all our arithmetic just as before, except
  282. that now it's all cluttered up with Xs. For example, suppose we wanted
  283. to multiply 1101 by 1011. We can do this simply by multiplying the
  284. polynomials:
  285.  
  286. (x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
  287. = (x^6 + x^4 + x^3
  288.  + x^5 + x^3 + x^2
  289.  + x^3 + x^1 + x^0) = x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
  290.  
  291. At this point, to get the right answer, we have to pretend that x is 2
  292. and propagate binary carries from the 3*x^3 yielding
  293.  
  294.    x^7 + x^3 + x^2 + x^1 + x^0
  295.  
  296. It's just like ordinary arithmetic except that the base is abstracted
  297. and brought into all the calculations explicitly instead of being
  298. there implicitly. So what's the point?
  299.  
  300. The point is that IF we pretend that we DON'T know what x is, we CAN'T
  301. perform the carries. We don't know that 3*x^3 is the same as x^4 + x^3
  302. because we don't know that x is 2. In this true polynomial arithmetic
  303. the relationship between all the coefficients is unknown and so the
  304. coefficients of each power effectively become strongly typed;
  305. coefficients of x^2 are effectively of a different type to
  306. coefficients of x^3.
  307.  
  308. With the coefficients of each power nicely isolated, mathematicians
  309. came up with all sorts of different kinds of polynomial arithmetics
  310. simply by changing the rules about how coefficients work. Of these
  311. schemes, one in particular is relevant here, and that is a polynomial
  312. arithmetic where the coefficients are calculated MOD 2 and there is no
  313. carry; all coefficients must be either 0 or 1 and no carries are
  314. calculated. This is called "polynomial arithmetic mod 2". Thus,
  315. returning to the earlier example:
  316.  
  317. (x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
  318. = (x^6 + x^4 + x^3
  319.  + x^5 + x^3 + x^2
  320.  + x^3 + x^1 + x^0)
  321. = x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
  322.  
  323. Under the other arithmetic, the 3*x^3 term was propagated using the
  324. carry mechanism using the knowledge that x=2. Under "polynomial
  325. arithmetic mod 2", we don't know what x is, there are no carries, and
  326. all coefficients have to be calculated mod 2. Thus, the result
  327. becomes:
  328.  
  329. = x^6 + x^5 + x^4 + x^3 + x^2 + x^1 + x^0
  330.  
  331. As Knuth [Knuth81] says (p.400):
  332.  
  333.    "The reader should note the similarity between polynomial
  334.    arithmetic and multiple-precision arithmetic (Section 4.3.1), where
  335.    the radix b is substituted for x. The chief difference is that the
  336.    coefficient u_k of x^k in polynomial arithmetic bears little or no
  337.    relation to its neighboring coefficients x^{k-1} [and x^{k+1}], so
  338.    the idea of "carrying" from one place to another is absent. In fact
  339.    polynomial arithmetic modulo b is essentially identical to multiple
  340.    precision arithmetic with radix b, except that all carries are
  341.    suppressed."
  342.  
  343. Thus polynomial arithmetic mod 2 is just binary arithmetic mod 2 with
  344. no carries. While polynomials provide useful mathematical machinery in
  345. more analytical approaches to CRC and error-correction algorithms, for
  346. the purposes of exposition they provide no extra insight and some
  347. encumbrance and have been discarded in the remainder of this document
  348. in favour of direct manipulation of the arithmetical system with which
  349. they are isomorphic: binary arithmetic with no carry.
  350.  
  351.  
  352. 5. Binary Arithmetic with No Carries
  353. ------------------------------------
  354. Having dispensed with polynomials, we can focus on the real arithmetic
  355. issue, which is that all the arithmetic performed during CRC
  356. calculations is performed in binary with no carries. Often this is
  357. called polynomial arithmetic, but as I have declared the rest of this
  358. document a polynomial free zone, we'll have to call it CRC arithmetic
  359. instead. As this arithmetic is a key part of CRC calculations, we'd
  360. better get used to it. Here we go:
  361.  
  362. Adding two numbers in CRC arithmetic is the same as adding numbers in
  363. ordinary binary arithmetic except there is no carry. This means that
  364. each pair of corresponding bits determine the corresponding output bit
  365. without reference to any other bit positions. For example:
  366.  
  367.         10011011
  368.        +11001010
  369.         --------
  370.         01010001
  371.         --------
  372.  
  373. There are only four cases for each bit position:
  374.  
  375.    0+0=0
  376.    0+1=1
  377.    1+0=1
  378.    1+1=0  (no carry)
  379.  
  380. Subtraction is identical:
  381.  
  382.         10011011
  383.        -11001010
  384.         --------
  385.         01010001
  386.         --------
  387.  
  388. with
  389.  
  390.    0-0=0
  391.    0-1=1  (wraparound)
  392.    1-0=1
  393.    1-1=0
  394.  
  395. In fact, both addition and subtraction in CRC arithmetic is equivalent
  396. to the XOR operation, and the XOR operation is its own inverse. This
  397. effectively reduces the operations of the first level of power
  398. (addition, subtraction) to a single operation that is its own inverse.
  399. This is a very convenient property of the arithmetic.
  400.  
  401. By collapsing of addition and subtraction, the arithmetic discards any
  402. notion of magnitude beyond the power of its highest one bit. While it
  403. seems clear that 1010 is greater than 10, it is no longer the case
  404. that 1010 can be considered to be greater than 1001. To see this, note
  405. that you can get from 1010 to 1001 by both adding and subtracting the
  406. same quantity:
  407.  
  408.    1010 = 1010 + 0011
  409.    1010 = 1010 - 0011
  410.  
  411. This makes nonsense of any notion of order.
  412.  
  413. Having defined addition, we can move to multiplication and division.
  414. Multiplication is absolutely straightforward, being the sum of the
  415. first number, shifted in accordance with the second number.
  416.  
  417.         1101
  418.       x 1011
  419.         ----
  420.         1101
  421.        1101.
  422.       0000..
  423.      1101...
  424.      -------
  425.      1111111  Note: The sum uses CRC addition
  426.      -------
  427.  
  428. Division is a little messier as we need to know when "a number goes
  429. into another number". To do this, we invoke the weak definition of
  430. magnitude defined earlier: that X is greater than or equal to Y iff
  431. the position of the highest 1 bit of X is the same or greater than the
  432. position of the highest 1 bit of Y. Here's a fully worked division
  433. (nicked from [Tanenbaum81]).
  434.  
  435.             1100001010
  436.        _______________
  437. 10011 ) 11010110110000
  438.         10011,,.,,....
  439.         -----,,.,,....
  440.          10011,.,,....
  441.          10011,.,,....
  442.          -----,.,,....
  443.           00001.,,....
  444.           00000.,,....
  445.           -----.,,....
  446.            00010,,....
  447.            00000,,....
  448.            -----,,....
  449.             00101,....
  450.             00000,....
  451.             -----,....
  452.              01011....
  453.              00000....
  454.              -----....
  455.               10110...
  456.               10011...
  457.               -----...
  458.                01010..
  459.                00000..
  460.                -----..
  461.                 10100.
  462.                 10011.
  463.                 -----.
  464.                  01110
  465.                  00000
  466.                  -----
  467.                   1110 = Remainder
  468.  
  469. That's really it. Before proceeding further, however, it's worth our
  470. while playing with this arithmetic a bit to get used to it.
  471.  
  472. We've already played with addition and subtraction, noticing that they
  473. are the same thing. Here, though, we should note that in this
  474. arithmetic A+0=A and A-0=A. This obvious property is very useful
  475. later.
  476.  
  477. In dealing with CRC multiplication and division, it's worth getting a
  478. feel for the concepts of MULTIPLE and DIVISIBLE.
  479.  
  480. If a number A is a multiple of B then what this means in CRC
  481. arithmetic is that it is possible to construct A from zero by XORing
  482. in various shifts of B. For example, if A was 0111010110 and B was 11,
  483. we could construct A from B as follows:
  484.  
  485.                   0111010110
  486.                 = .......11.
  487.                 + ....11....
  488.                 + ...11.....
  489.                   .11.......
  490.  
  491. However, if A is 0111010111, it is not possible to construct it out of
  492. various shifts of B (can you see why? - see later) so it is said to be
  493. not divisible by B in CRC arithmetic.
  494.  
  495. Thus we see that CRC arithmetic is primarily about XORing particular
  496. values at various shifting offsets.
  497.  
  498.  
  499. 6. A Fully Worked Example
  500. -------------------------
  501. Having defined CRC arithmetic, we can now frame a CRC calculation as
  502. simply a division, because that's all it is! This section fills in the
  503. details and gives an example.
  504.  
  505. To perform a CRC calculation, we need to choose a divisor. In maths
  506. marketing speak the divisor is called the "generator polynomial" or
  507. simply the "polynomial", and is a key parameter of any CRC algorithm.
  508. It would probably be more friendly to call the divisor something else,
  509. but the poly talk is so deeply ingrained in the field that it would
  510. now be confusing to avoid it. As a compromise, we will refer to the
  511. CRC polynomial as the "poly". Just think of this number as a sort of
  512. parrot. "Hello poly!"
  513.  
  514. You can choose any poly and come up with a CRC algorithm. However,
  515. some polys are better than others, and so it is wise to stick with the
  516. tried an tested ones. A later section addresses this issue.
  517.  
  518. The width (position of the highest 1 bit) of the poly is very
  519. important as it dominates the whole calculation. Typically, widths of
  520. 16 or 32 are chosen so as to simplify implementation on modern
  521. computers. The width of a poly is the actual bit position of the
  522. highest bit. For example, the width of 10011 is 4, not 5. For the
  523. purposes of example, we will chose a poly of 10011 (of width W of 4).
  524.  
  525. Having chosen a poly, we can proceed with the calculation. This is
  526. simply a division (in CRC arithmetic) of the message by the poly. The
  527. only trick is that W zero bits are appended to the message before the
  528. CRC is calculated. Thus we have:
  529.  
  530.    Original message                : 1101011011
  531.    Poly                            :      10011
  532.    Message after appending W zeros : 11010110110000
  533.  
  534. Now we simply divide the augmented message by the poly using CRC
  535. arithmetic. This is the same division as before:
  536.  
  537.             1100001010 = Quotient (nobody cares about the quotient)
  538.        _______________
  539. 10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
  540. =Poly  10011,,.,,....
  541.         -----,,.,,....
  542.          10011,.,,....
  543.          10011,.,,....
  544.          -----,.,,....
  545.           00001.,,....
  546.           00000.,,....
  547.           -----.,,....
  548.            00010,,....
  549.            00000,,....
  550.            -----,,....
  551.             00101,....
  552.             00000,....
  553.             -----,....
  554.              01011....
  555.              00000....
  556.              -----....
  557.               10110...
  558.               10011...
  559.               -----...
  560.                01010..
  561.                00000..
  562.                -----..
  563.                 10100.
  564.                 10011.
  565.                 -----.
  566.                  01110
  567.                  00000
  568.                  -----
  569.                   1110 = Remainder = THE CHECKSUM!!!!
  570.  
  571. The division yields a quotient, which we throw away, and a remainder,
  572. which is the calculated checksum. This ends the calculation.
  573.  
  574. Usually, the checksum is then appended to the message and the result
  575. transmitted. In this case the transmission would be: 11010110111110.
  576.  
  577. At the other end, the receiver can do one of two things:
  578.  
  579.    a. Separate the message and checksum. Calculate the checksum for
  580.       the message (after appending W zeros) and compare the two
  581.       checksums.
  582.  
  583.    b. Checksum the whole lot (without appending zeros) and see if it
  584.       comes out as zero!
  585.  
  586. These two options are equivalent. However, in the next section, we
  587. will be assuming option b because it is marginally mathematically
  588. cleaner.
  589.  
  590. A summary of the operation of the class of CRC algorithms:
  591.  
  592.    1. Choose a width W, and a poly G (of width W).
  593.    2. Append W zero bits to the message. Call this M'.
  594.    3. Divide M' by G using CRC arithmetic. The remainder is the checksum.
  595.  
  596. That's all there is to it.
  597.  
  598.  
  599. 7. Choosing A Poly
  600. ------------------
  601. Choosing a poly is somewhat of a black art and the reader is referred
  602. to [Tanenbaum81] (p.130-132) which has a very clear discussion of this
  603. issue. This section merely aims to put the fear of death into anyone
  604. who so much as toys with the idea of making up their own poly. If you
  605. don't care about why one poly might be better than another and just
  606. want to find out about high-speed implementations, choose one of the
  607. arithmetically sound polys listed at the end of this section and skip
  608. to the next section.
  609.  
  610. First note that the transmitted message T is a multiple of the poly.
  611. To see this, note that 1) the last W bits of T is the remainder after
  612. dividing the augmented (by zeros remember) message by the poly, and 2)
  613. addition is the same as subtraction so adding the remainder pushes the
  614. value up to the next multiple. Now note that if the transmitted
  615. message is corrupted in transmission that we will receive T+E where E
  616. is an error vector (and + is CRC addition (i.e. XOR)). Upon receipt of
  617. this message, the receiver divides T+E by G. As T mod G is 0, (T+E)
  618. mod G = E mod G. Thus, the capacity of the poly we choose to catch
  619. particular kinds of errors will be determined by the set of multiples
  620. of G, for any corruption E that is a multiple of G will be undetected.
  621. Our task then is to find classes of G whose multiples look as little
  622. like the kind of line noise (that will be creating the corruptions) as
  623. possible. So let's examine the kinds of line noise we can expect.
  624.  
  625. SINGLE BIT ERRORS: A single bit error means E=1000...0000. We can
  626. ensure that this class of error is always detected by making sure that
  627. G has at least two bits set to 1. Any multiple of G will be
  628. constructed using shifting and adding and it is impossible to
  629. construct a value with a single bit by shifting an adding a single
  630. value with more than one bit set, as the two end bits will always
  631. persist.
  632.  
  633. TWO-BIT ERRORS: To detect all errors of the form 100...000100...000
  634. (i.e. E contains two 1 bits) choose a G that does not have multiples
  635. that are 11, 101, 1001, 10001, 100001, etc. It is not clear to me how
  636. one goes about doing this (I don't have the pure maths background),
  637. but Tanenbaum assures us that such G do exist, and cites G with 1 bits
  638. (15,14,1) turned on as an example of one G that won't divide anything
  639. less than 1...1 where ... is 32767 zeros.
  640.  
  641. ERRORS WITH AN ODD NUMBER OF BITS: We can catch all corruptions where
  642. E has an odd number of bits by choosing a G that has an even number of
  643. bits. To see this, note that 1) CRC multiplication is simply XORing a
  644. constant value into a register at various offsets, 2) XORing is simply
  645. a bit-flip operation, and 3) if you XOR a value with an even number of
  646. bits into a register, the oddness of the number of 1 bits in the
  647. register remains invariant. Example: Starting with E=111, attempt to
  648. flip all three bits to zero by the repeated application of XORing in
  649. 11 at one of the two offsets (i.e. "E=E XOR 011" and "E=E XOR 110")
  650. This is nearly isomorphic to the "glass tumblers" party puzzle where
  651. you challenge someone to flip three tumblers by the repeated
  652. application of the operation of flipping any two. Most of the popular
  653. CRC polys contain an even number of 1 bits. (Note: Tanenbaum states
  654. more specifically that all errors with an odd number of bits can be
  655. caught by making G a multiple of 11).
  656.  
  657. BURST ERRORS: A burst error looks like E=000...000111...11110000...00.
  658. That is, E consists of all zeros except for a run of 1s somewhere
  659. inside. This can be recast as E=(10000...00)(1111111...111) where
  660. there are z zeros in the LEFT part and n ones in the RIGHT part. To
  661. catch errors of this kind, we simply set the lowest bit of G to 1.
  662. Doing this ensures that LEFT cannot be a factor of G. Then, so long as
  663. G is wider than RIGHT, the error will be detected. See Tanenbaum for a
  664. clearer explanation of this; I'm a little fuzzy on this one. Note:
  665. Tanenbaum asserts that the probability of a burst of length greater
  666. than W getting through is (0.5)^W.
  667.  
  668. That concludes the section on the fine art of selecting polys.
  669.  
  670. Some popular polys are:
  671. 16 bits: (16,12,5,0)                                [X25 standard]
  672.          (16,15,2,0)                                ["CRC-16"]
  673. 32 bits: (32,26,23,22,16,12,11,10,8,7,5,4,2,1,0)    [Ethernet]
  674.  
  675.  
  676. 8. A Straightforward CRC Implementation
  677. ---------------------------------------
  678. That's the end of the theory; now we turn to implementations. To start
  679. with, we examine an absolutely straight-down-the-middle boring
  680. straightforward low-speed implementation that doesn't use any speed
  681. tricks at all. We'll then transform that program progressively until we
  682. end up with the compact table-driven code we all know and love and
  683. which some of us would like to understand.
  684.  
  685. To implement a CRC algorithm all we have to do is implement CRC
  686. division. There are two reasons why we cannot simply use the divide
  687. instruction of whatever machine we are on. The first is that we have
  688. to do the divide in CRC arithmetic. The second is that the dividend
  689. might be ten megabytes long, and today's processors do not have
  690. registers that big.
  691.  
  692. So to implement CRC division, we have to feed the message through a
  693. division register. At this point, we have to be absolutely precise
  694. about the message data. In all the following examples the message will
  695. be considered to be a stream of bytes (each of 8 bits) with bit 7 of
  696. each byte being considered to be the most significant bit (MSB). The
  697. bit stream formed from these bytes will be the bit stream with the MSB
  698. (bit 7) of the first byte first, going down to bit 0 of the first
  699. byte, and then the MSB of the second byte and so on.
  700.  
  701. With this in mind, we can sketch an implementation of the CRC
  702. division. For the purposes of example, consider a poly with W=4 and
  703. the poly=10111. Then, to perform the division, we need to use a 4-bit
  704. register:
  705.  
  706.                   3   2   1   0   Bits
  707.                 +---+---+---+---+
  708.        Pop! <-- |   |   |   |   | <----- Augmented message
  709.                 +---+---+---+---+
  710.  
  711.              1    0   1   1   1   = The Poly
  712.  
  713. (Reminder: The augmented message is the message followed by W zero bits.)
  714.  
  715. To perform the division perform the following:
  716.  
  717.    Load the register with zero bits.
  718.    Augment the message by appending W zero bits to the end of it.
  719.    While (more message bits)
  720.       Begin
  721.       Shift the register left by one bit, reading the next bit of the
  722.          augmented message into register bit position 0.
  723.       If (a 1 bit popped out of the register during step 3)
  724.          Register = Register XOR Poly.
  725.       End
  726.    The register now contains the remainder.
  727.  
  728. (Note: In practice, the IF condition can be tested by testing the top
  729.  bit of R before performing the shift.)
  730.  
  731. We will call this algorithm "SIMPLE".
  732.  
  733. This might look a bit messy, but all we are really doing is
  734. "subtracting" various powers (i.e. shiftings) of the poly from the
  735. message until there is nothing left but the remainder. Study the
  736. manual examples of long division if you don't understand this.
  737.  
  738. It should be clear that the above algorithm will work for any width W.
  739.  
  740.  
  741. 9. A Table-Driven Implementation
  742. --------------------------------
  743. The SIMPLE algorithm above is a good starting point because it
  744. corresponds directly to the theory presented so far, and because it is
  745. so SIMPLE. However, because it operates at the bit level, it is rather
  746. awkward to code (even in C), and inefficient to execute (it has to
  747. loop once for each bit). To speed it up, we need to find a way to
  748. enable the algorithm to process the message in units larger than one
  749. bit. Candidate quantities are nibbles (4 bits), bytes (8 bits), words
  750. (16 bits) and longwords (32 bits) and higher if we can achieve it. Of
  751. these, 4 bits is best avoided because it does not correspond to a byte
  752. boundary. At the very least, any speedup should allow us to operate at
  753. byte boundaries, and in fact most of the table driven algorithms
  754. operate a byte at a time.
  755.  
  756. For the purposes of discussion, let us switch from a 4-bit poly to a
  757. 32-bit one. Our register looks much the same, except the boxes
  758. represent bytes instead of bits, and the Poly is 33 bits (one implicit
  759. 1 bit at the top and 32 "active" bits) (W=32).
  760.  
  761.                    3    2    1    0   Bytes
  762.                 +----+----+----+----+
  763.        Pop! <-- |    |    |    |    | <----- Augmented message
  764.                 +----+----+----+----+
  765.  
  766.                1<------32 bits------>
  767.  
  768. The SIMPLE algorithm is still applicable. Let us examine what it does.
  769. Imagine that the SIMPLE algorithm is in full swing and consider the
  770. top 8 bits of the 32-bit register (byte 3) to have the values:
  771.  
  772.    t7 t6 t5 t4 t3 t2 t1 t0
  773.  
  774. In the next iteration of SIMPLE, t7 will determine whether the Poly
  775. will be XORed into the entire register. If t7=1, this will happen,
  776. otherwise it will not. Suppose that the top 8 bits of the poly are g7
  777. g6.. g0, then after the next iteration, the top byte will be:
  778.  
  779.         t6 t5 t4 t3 t2 t1 t0 ??
  780. + t7 * (g7 g6 g5 g4 g3 g2 g1 g0)    [Reminder: + is XOR]
  781.  
  782. The NEW top bit (that will control what happens in the next iteration)
  783. now has the value t6 + t7*g7. The important thing to notice here is
  784. that from an informational point of view, all the information required
  785. to calculate the NEW top bit was present in the top TWO bits of the
  786. original top byte. Similarly, the NEXT top bit can be calculated in
  787. advance SOLELY from the top THREE bits t7, t6, and t5. In fact, in
  788. general, the value of the top bit in the register in k iterations can
  789. be calculated from the top k bits of the register. Let us take this
  790. for granted for a moment.
  791.  
  792. Consider for a moment that we use the top 8 bits of the register to
  793. calculate the value of the top bit of the register during the next 8
  794. iterations. Suppose that we drive the next 8 iterations using the
  795. calculated values (which we could perhaps store in a single byte
  796. register and shift out to pick off each bit). Then we note three
  797. things:
  798.  
  799.    * The top byte of the register now doesn't matter. No matter how
  800.      many times and at what offset the poly is XORed to the top 8
  801.      bits, they will all be shifted out the right hand side during the
  802.      next 8 iterations anyway.
  803.  
  804.  
  805.    * The remaining bits will be shifted left one position and the
  806.      rightmost byte of the register will be shifted in the next byte
  807.  
  808.    AND
  809.  
  810.    * While all this is going on, the register will be subjected to a
  811.      series of XOR's in accordance with the bits of the pre-calculated
  812.      control byte.
  813.  
  814. Now consider the effect of XORing in a constant value at various
  815. offsets to a register. For example:
  816.  
  817.        0100010  Register
  818.        ...0110  XOR this
  819.        ..0110.  XOR this
  820.        0110...  XOR this
  821.        -------
  822.        0011000
  823.        -------
  824.  
  825. The point of this is that you can XOR constant values into a register
  826. to your heart's delight, and in the end, there will exist a value
  827. which when XORed in with the original register will have the same
  828. effect as all the other XORs.
  829.  
  830. Perhaps you can see the solution now. Putting all the pieces together
  831. we have an algorithm that goes like this:
  832.  
  833.    While (augmented message is not exhausted)
  834.       Begin
  835.       Examine the top byte of the register
  836.       Calculate the control byte from the top byte of the register
  837.       Sum all the Polys at various offsets that are to be XORed into
  838.          the register in accordance with the control byte
  839.       Shift the register left by one byte, reading a new message byte
  840.          into the rightmost byte of the register
  841.       XOR the summed polys to the register
  842.       End
  843.  
  844. As it stands this is not much better than the SIMPLE algorithm.
  845. However, it turns out that most of the calculation can be precomputed
  846. and assembled into a table. As a result, the above algorithm can be
  847. reduced to:
  848.  
  849.    While (augmented message is not exhausted)
  850.       Begin
  851.       Top = top_byte(Register);
  852.       Register = (Register << 24) | next_augmessage_byte;
  853.       Register = Register XOR precomputed_table[Top];
  854.       End
  855.  
  856. There! If you understand this, you've grasped the main idea of
  857. table-driven CRC algorithms. The above is a very efficient algorithm
  858. requiring just a shift, and OR, an XOR, and a table lookup per byte.
  859. Graphically, it looks like this:
  860.  
  861.                    3    2    1    0   Bytes
  862.                 +----+----+----+----+
  863.          +-----<|    |    |    |    | <----- Augmented message
  864.          |      +----+----+----+----+
  865.          |                ^
  866.          |                |
  867.          |               XOR
  868.          |                |
  869.          |     0+----+----+----+----+       Algorithm
  870.          v      +----+----+----+----+       ---------
  871.          |      +----+----+----+----+       1. Shift the register left by
  872.          |      +----+----+----+----+          one byte, reading in a new
  873.          |      +----+----+----+----+          message byte.
  874.          |      +----+----+----+----+       2. Use the top byte just rotated
  875.          |      +----+----+----+----+          out of the register to index
  876.          +----->+----+----+----+----+          the table of 256 32-bit values.
  877.                 +----+----+----+----+       3. XOR the table value into the
  878.                 +----+----+----+----+          register.
  879.                 +----+----+----+----+       4. Goto 1 iff more augmented
  880.                 +----+----+----+----+          message bytes.
  881.              255+----+----+----+----+
  882.  
  883.  
  884. In C, the algorithm main loop looks like this:
  885.  
  886.    r=0;
  887.    while (len--)
  888.      {
  889.       byte t = (r >> 24) & 0xFF;
  890.       r = (r << 8) | *p++;
  891.       r^=table[t];
  892.      }
  893.  
  894. where len is the length of the augmented message in bytes, p points to
  895. the augmented message, r is the register, t is a temporary, and table
  896. is the computed table. This code can be made even more unreadable as
  897. follows:
  898.  
  899.    r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
  900.  
  901. This is a very clean, efficient loop, although not a very obvious one
  902. to the casual observer not versed in CRC theory. We will call this the
  903. TABLE algorithm.
  904.  
  905.  
  906. 10. A Slightly Mangled Table-Driven Implementation
  907. --------------------------------------------------
  908. Despite the terse beauty of the line
  909.  
  910.    r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
  911.  
  912. those optimizing hackers couldn't leave it alone. The trouble, you
  913. see, is that this loop operates upon the AUGMENTED message and in
  914. order to use this code, you have to append W/8 zero bytes to the end
  915. of the message before pointing p at it. Depending on the run-time
  916. environment, this may or may not be a problem; if the block of data
  917. was handed to us by some other code, it could be a BIG problem. One
  918. alternative is simply to append the following line after the above
  919. loop, once for each zero byte:
  920.  
  921.       for (i=0; i<W/4; i++) r = (r << 8) ^ t[(r >> 24) & 0xFF];
  922.  
  923. This looks like a sane enough solution to me. However, at the further
  924. expense of clarity (which, you must admit, is already a pretty scare
  925. commodity in this code) we can reorganize this small loop further so
  926. as to avoid the need to either augment the message with zero bytes, or
  927. to explicitly process zero bytes at the end as above. To explain the
  928. optimization, we return to the processing diagram given earlier.
  929.  
  930.                    3    2    1    0   Bytes
  931.                 +----+----+----+----+
  932.          +-----<|    |    |    |    | <----- Augmented message
  933.          |      +----+----+----+----+
  934.          |                ^
  935.          |                |
  936.          |               XOR
  937.          |                |
  938.          |     0+----+----+----+----+       Algorithm
  939.          v      +----+----+----+----+       ---------
  940.          |      +----+----+----+----+       1. Shift the register left by
  941.          |      +----+----+----+----+          one byte, reading in a new
  942.          |      +----+----+----+----+          message byte.
  943.          |      +----+----+----+----+       2. Use the top byte just rotated
  944.          |      +----+----+----+----+          out of the register to index
  945.          +----->+----+----+----+----+          the table of 256 32-bit values.
  946.                 +----+----+----+----+       3. XOR the table value into the
  947.                 +----+----+----+----+          register.
  948.                 +----+----+----+----+       4. Goto 1 iff more augmented
  949.                 +----+----+----+----+          message bytes.
  950.              255+----+----+----+----+
  951.  
  952. Now, note the following facts:
  953.  
  954. TAIL: The W/4 augmented zero bytes that appear at the end of the
  955.       message will be pushed into the register from the right as all
  956.       the other bytes are, but their values (0) will have no effect
  957.       whatsoever on the register because 1) XORing with zero does not
  958.       change the target byte, and 2) the four bytes are never
  959.       propagated out the left side of the register where their
  960.       zeroness might have some sort of influence. Thus, the sole
  961.       function of the W/4 augmented zero bytes is to drive the
  962.       calculation for another W/4 byte cycles so that the end of the
  963.       REAL data passes all the way through the register.
  964.  
  965. HEAD: If the initial value of the register is zero, the first four
  966.       iterations of the loop will have the sole effect of shifting in
  967.       the first four bytes of the message from the right. This is
  968.       because the first 32 control bits are all zero and so nothing is
  969.       XORed into the register. Even if the initial value is not zero,
  970.       the first 4 byte iterations of the algorithm will have the sole
  971.       effect of shifting the first 4 bytes of the message into the
  972.       register and then XORing them with some constant value (that is
  973.       a function of the initial value of the register).
  974.  
  975. These facts, combined with the XOR property
  976.  
  977.    (A xor B) xor C = A xor (B xor C)
  978.  
  979. mean that message bytes need not actually travel through the W/4 bytes
  980. of the register. Instead, they can be XORed into the top byte just
  981. before it is used to index the lookup table. This leads to the
  982. following modified version of the algorithm.
  983.  
  984.  
  985.          +-----<Message (non augmented)
  986.          |
  987.          v         3    2    1    0   Bytes
  988.          |      +----+----+----+----+
  989.         XOR----<|    |    |    |    |
  990.          |      +----+----+----+----+
  991.          |                ^
  992.          |                |
  993.          |               XOR
  994.          |                |
  995.          |     0+----+----+----+----+       Algorithm
  996.          v      +----+----+----+----+       ---------
  997.          |      +----+----+----+----+       1. Shift the register left by
  998.          |      +----+----+----+----+          one byte, reading in a new
  999.          |      +----+----+----+----+          message byte.
  1000.          |      +----+----+----+----+       2. XOR the top byte just rotated
  1001.          |      +----+----+----+----+          out of the register with the
  1002.          +----->+----+----+----+----+          next message byte to yield an
  1003.                 +----+----+----+----+          index into the table ([0,255]).
  1004.                 +----+----+----+----+       3. XOR the table value into the
  1005.                 +----+----+----+----+          register.
  1006.                 +----+----+----+----+       4. Goto 1 iff more augmented
  1007.              255+----+----+----+----+          message bytes.
  1008.  
  1009.  
  1010. Note: The initial register value for this algorithm must be the
  1011. initial value of the register for the previous algorithm fed through
  1012. the table four times. Note: The table is such that if the previous
  1013. algorithm used 0, the new algorithm will too.
  1014.  
  1015. This is an IDENTICAL algorithm and will yield IDENTICAL results. The C
  1016. code looks something like this:
  1017.  
  1018.    r=0; while (len--) r = (r<<8) ^ t[(r >> 24) ^ *p++];
  1019.  
  1020. and THIS is the code that you are likely to find inside current
  1021. table-driven CRC implementations. Some FF masks might have to be ANDed
  1022. in here and there for portability's sake, but basically, the above
  1023. loop is IT. We will call this the DIRECT TABLE ALGORITHM.
  1024.  
  1025. During the process of trying to understand all this stuff, I managed
  1026. to derive the SIMPLE algorithm and the table-driven version derived
  1027. from that. However, when I compared my code with the code found in
  1028. real-implementations, I was totally bamboozled as to why the bytes
  1029. were being XORed in at the wrong end of the register! It took quite a
  1030. while before I figured out that theirs and my algorithms were actually
  1031. the same. Part of why I am writing this document is that, while the
  1032. link between division and my earlier table-driven code is vaguely
  1033. apparent, any such link is fairly well erased when you start pumping
  1034. bytes in at the "wrong end" of the register. It looks all wrong!
  1035.  
  1036. If you've got this far, you not only understand the theory, the
  1037. practice, the optimized practice, but you also understand the real
  1038. code you are likely to run into. Could get any more complicated? Yes
  1039. it can.
  1040.  
  1041.  
  1042. 11. "Reflected" Table-Driven Implementations
  1043. --------------------------------------------
  1044. Despite the fact that the above code is probably optimized about as
  1045. much as it could be, this did not stop some enterprising individuals
  1046. from making things even more complicated. To understand how this
  1047. happened, we have to enter the world of hardware.
  1048.  
  1049. DEFINITION: A value/register is reflected if it's bits are swapped
  1050. around its centre. For example: 0101 is the 4-bit reflection of 1010.
  1051. 0011 is the reflection of 1100.
  1052. 0111-0101-1010-1111-0010-0101-1011-1100 is the reflection of
  1053. 0011-1101-1010-0100-1111-0101-1010-1110.
  1054.  
  1055. Turns out that UARTs (those handy little chips that perform serial IO)
  1056. are in the habit of transmitting each byte with the least significant
  1057. bit (bit 0) first and the most significant bit (bit 7) last (i.e.
  1058. reflected). An effect of this convention is that hardware engineers
  1059. constructing hardware CRC calculators that operate at the bit level
  1060. took to calculating CRCs of bytes streams with each of the bytes
  1061. reflected within itself. The bytes are processed in the same order,
  1062. but the bits in each byte are swapped; bit 0 is now bit 7, bit 1 is
  1063. now bit 6, and so on. Now this wouldn't matter much if this convention
  1064. was restricted to hardware land. However it seems that at some stage
  1065. some of these CRC values were presented at the software level and
  1066. someone had to write some code that would interoperate with the
  1067. hardware CRC calculation.
  1068.  
  1069. In this situation, a normal sane software engineer would simply
  1070. reflect each byte before processing it. However, it would seem that
  1071. normal sane software engineers were thin on the ground when this early
  1072. ground was being broken, because instead of reflecting the bytes,
  1073. whoever was responsible held down the byte and reflected the world,
  1074. leading to the following "reflected" algorithm which is identical to
  1075. the previous one except that everything is reflected except the input
  1076. bytes.
  1077.  
  1078.  
  1079.              Message (non augmented) >-----+
  1080.                                            |
  1081.            Bytes   0    1    2    3        v
  1082.                 +----+----+----+----+      |
  1083.                 |    |    |    |    |>----XOR
  1084.                 +----+----+----+----+      |
  1085.                           ^                |
  1086.                           |                |
  1087.                          XOR               |
  1088.                           |                |
  1089.                 +----+----+----+----+0     |
  1090.                 +----+----+----+----+      v
  1091.                 +----+----+----+----+      |
  1092.                 +----+----+----+----+      |
  1093.                 +----+----+----+----+      |
  1094.                 +----+----+----+----+      |
  1095.                 +----+----+----+----+      |
  1096.                 +----+----+----+----+<-----+
  1097.                 +----+----+----+----+
  1098.                 +----+----+----+----+
  1099.                 +----+----+----+----+
  1100.                 +----+----+----+----+
  1101.                 +----+----+----+----+255
  1102.  
  1103. Notes:
  1104.  
  1105.    * The table is identical to the one in the previous algorithm
  1106.    except that each entry has been reflected.
  1107.  
  1108.    * The initial value of the register is the same as in the previous
  1109.    algorithm except that it has been reflected.
  1110.  
  1111.    * The bytes of the message are processed in the same order as
  1112.    before (i.e. the message itself is not reflected).
  1113.  
  1114.    * The message bytes themselves don't need to be explicitly
  1115.    reflected, because everything else has been!
  1116.  
  1117. At the end of execution, the register contains the reflection of the
  1118. final CRC value (remainder). Actually, I'm being rather hard on
  1119. whoever cooked this up because it seems that hardware implementations
  1120. of the CRC algorithm used the reflected checksum value and so
  1121. producing a reflected CRC was just right. In fact reflecting the world
  1122. was probably a good engineering solution - if a confusing one.
  1123.  
  1124. We will call this the REFLECTED algorithm.
  1125.  
  1126. Whether or not it made sense at the time, the effect of having
  1127. reflected algorithms kicking around the world's FTP sites is that
  1128. about half the CRC implementations one runs into are reflected and the
  1129. other half not. It's really terribly confusing. In particular, it
  1130. would seem to me that the casual reader who runs into a reflected,
  1131. table-driven implementation with the bytes "fed in the wrong end"
  1132. would have Buckley's chance of ever connecting the code to the concept
  1133. of binary mod 2 division.
  1134.  
  1135. It couldn't get any more confusing could it? Yes it could.
  1136.  
  1137.  
  1138. 12. "Reversed" Polys
  1139. --------------------
  1140. As if reflected implementations weren't enough, there is another
  1141. concept kicking around which makes the situation bizarrely confusing.
  1142. The concept is reversed Polys.
  1143.  
  1144. It turns out that the reflection of good polys tend to be good polys
  1145. too! That is, if G=11101 is a good poly value, then 10111 will be as
  1146. well. As a consequence, it seems that every time an organization (such
  1147. as CCITT) standardizes on a particularly good poly ("polynomial"),
  1148. those in the real world can't leave the poly's reflection alone
  1149. either. They just HAVE to use it. As a result, the set of "standard"
  1150. poly's has a corresponding set of reflections, which are also in use.
  1151. To avoid confusion, we will call these the "reversed" polys.
  1152.  
  1153.    X25   standard: 1-0001-0000-0010-0001
  1154.    X25   reversed: 1-0000-1000-0001-0001
  1155.  
  1156.    CRC16 standard: 1-1000-0000-0000-0101
  1157.    CRC16 reversed: 1-0100-0000-0000-0011
  1158.  
  1159. Note that here it is the entire poly that is being reflected/reversed,
  1160. not just the bottom W bits. This is an important distinction. In the
  1161. reflected algorithm described in the previous section, the poly used
  1162. in the reflected algorithm was actually identical to that used in the
  1163. non-reflected algorithm; all that had happened is that the bytes had
  1164. effectively been reflected. As such, all the 16-bit/32-bit numbers in
  1165. the algorithm had to be reflected. In contrast, the ENTIRE poly
  1166. includes the implicit one bit at the top, and so reversing a poly is
  1167. not the same as reflecting its bottom 16 or 32 bits.
  1168.  
  1169. The upshot of all this is that a reflected algorithm is not equivalent
  1170. to the original algorithm with the poly reflected. Actually, this is
  1171. probably less confusing than if they were duals.
  1172.  
  1173. If all this seems a bit unclear, don't worry, because we're going to
  1174. sort it all out "real soon now". Just one more section to go before
  1175. that.
  1176.  
  1177.  
  1178. 13. Initial and Final Values
  1179. ----------------------------
  1180. In addition to the complexity already seen, CRC algorithms differ from
  1181. each other in two other regards:
  1182.  
  1183.    * The initial value of the register.
  1184.  
  1185.    * The value to be XORed with the final register value.
  1186.  
  1187. For example, the "CRC32" algorithm initializes its register to
  1188. FFFFFFFF and XORs the final register value with FFFFFFFF.
  1189.  
  1190. Most CRC algorithms initialize their register to zero. However, some
  1191. initialize it to a non-zero value. In theory (i.e. with no assumptions
  1192. about the message), the initial value has no affect on the strength of
  1193. the CRC algorithm, the initial value merely providing a fixed starting
  1194. point from which the register value can progress. However, in
  1195. practice, some messages are more likely than others, and it is wise to
  1196. initialize the CRC algorithm register to a value that does not have
  1197. "blind spots" that are likely to occur in practice. By "blind spot" is
  1198. meant a sequence of message bytes that do not result in the register
  1199. changing its value. In particular, any CRC algorithm that initializes
  1200. its register to zero will have a blind spot of zero when it starts up
  1201. and will be unable to "count" a leading run of zero bytes. As a
  1202. leading run of zero bytes is quite common in real messages, it is wise
  1203. to initialize the algorithm register to a non-zero value.
  1204.  
  1205.  
  1206. 14. Defining Algorithms Absolutely
  1207. ----------------------------------
  1208. At this point we have covered all the different aspects of
  1209. table-driven CRC algorithms. As there are so many variations on these
  1210. algorithms, it is worth trying to establish a nomenclature for them.
  1211. This section attempts to do that.
  1212.  
  1213. We have seen that CRC algorithms vary in:
  1214.  
  1215.    * Width of the poly (polynomial).
  1216.    * Value of the poly.
  1217.    * Initial value for the register.
  1218.    * Whether the bits of each byte are reflected before being processed.
  1219.    * Whether the algorithm feeds input bytes through the register or
  1220.      xors them with a byte from one end and then straight into the table.
  1221.    * Whether the final register value should be reversed (as in reflected
  1222.      versions).
  1223.    * Value to XOR with the final register value.
  1224.  
  1225. In order to be able to talk about particular CRC algorithms, we need
  1226. to be able to define them more precisely than this. For this reason, the
  1227. next section attempts to provide a well-defined parameterized model
  1228. for CRC algorithms. To refer to a particular algorithm, we need then
  1229. simply specify the algorithm in terms of parameters to the model.
  1230.  
  1231.  
  1232. 15. A Parameterized Model For CRC Algorithms
  1233. --------------------------------------------
  1234. In this section we define a precise parameterized model CRC algorithm
  1235. which, for want of a better name, we will call the "Rocksoft^tm Model
  1236. CRC Algorithm" (and why not? Rocksoft^tm could do with some free
  1237. advertising :-).
  1238.  
  1239. The most important aspect of the model algorithm is that it focusses
  1240. exclusively on functionality, ignoring all implementation details. The
  1241. aim of the exercise is to construct a way of referring precisely to
  1242. particular CRC algorithms, regardless of how confusingly they are
  1243. implemented. To this end, the model must be as simple and precise as
  1244. possible, with as little confusion as possible.
  1245.  
  1246. The Rocksoft^tm Model CRC Algorithm is based essentially on the DIRECT
  1247. TABLE ALGORITHM specified earlier. However, the algorithm has to be
  1248. further parameterized to enable it to behave in the same way as some
  1249. of the messier algorithms out in the real world.
  1250.  
  1251. To enable the algorithm to behave like reflected algorithms, we
  1252. provide a boolean option to reflect the input bytes, and a boolean
  1253. option to specify whether to reflect the output checksum value. By
  1254. framing reflection as an input/output transformation, we avoid the
  1255. confusion of having to mentally map the parameters of reflected and
  1256. non-reflected algorithms.
  1257.  
  1258. An extra parameter allows the algorithm's register to be initialized
  1259. to a particular value. A further parameter is XORed with the final
  1260. value before it is returned.
  1261.  
  1262. By putting all these pieces together we end up with the parameters of
  1263. the algorithm:
  1264.  
  1265.    NAME: This is a name given to the algorithm. A string value.
  1266.  
  1267.    WIDTH: This is the width of the algorithm expressed in bits. This
  1268.    is one less than the width of the Poly.
  1269.  
  1270.    POLY: This parameter is the poly. This is a binary value that
  1271.    should be specified as a hexadecimal number. The top bit of the
  1272.    poly should be omitted. For example, if the poly is 10110, you
  1273.    should specify 06. An important aspect of this parameter is that it
  1274.    represents the unreflected poly; the bottom bit of this parameter
  1275.    is always the LSB of the divisor during the division regardless of
  1276.    whether the algorithm being modelled is reflected.
  1277.  
  1278.    INIT: This parameter specifies the initial value of the register
  1279.    when the algorithm starts. This is the value that is to be assigned
  1280.    to the register in the direct table algorithm. In the table
  1281.    algorithm, we may think of the register always commencing with the
  1282.    value zero, and this value being XORed into the register after the
  1283.    N'th bit iteration. This parameter should be specified as a
  1284.    hexadecimal number.
  1285.  
  1286.    REFIN: This is a boolean parameter. If it is FALSE, input bytes are
  1287.    processed with bit 7 being treated as the most significant bit
  1288.    (MSB) and bit 0 being treated as the least significant bit. If this
  1289.    parameter is FALSE, each byte is reflected before being processed.
  1290.  
  1291.    REFOUT: This is a boolean parameter. If it is set to FALSE, the
  1292.    final value in the register is fed into the XOROUT stage directly,
  1293.    otherwise, if this parameter is TRUE, the final register value is
  1294.    reflected first.
  1295.  
  1296.    XOROUT: This is an W-bit value that should be specified as a
  1297.    hexadecimal number. It is XORed to the final register value (after
  1298.    the REFOUT) stage before the value is returned as the official
  1299.    checksum.
  1300.  
  1301.    CHECK: This field is not strictly part of the definition, and, in
  1302.    the event of an inconsistency between this field and the other
  1303.    field, the other fields take precedence. This field is a check
  1304.    value that can be used as a weak validator of implementations of
  1305.    the algorithm. The field contains the checksum obtained when the
  1306.    ASCII string "123456789" is fed through the specified algorithm
  1307.    (i.e. 313233... (hexadecimal)).
  1308.  
  1309. With these parameters defined, the model can now be used to specify a
  1310. particular CRC algorithm exactly. Here is an example specification for
  1311. a popular form of the CRC-16 algorithm.
  1312.  
  1313.    Name   : "CRC-16"
  1314.    Width  : 16
  1315.    Poly   : 8005
  1316.    Init   : 0000
  1317.    RefIn  : True
  1318.    RefOut : True
  1319.    XorOut : 0000
  1320.    Check  : BB3D
  1321.  
  1322.  
  1323. 16. A Catalog of Parameter Sets for Standards
  1324. ---------------------------------------------
  1325. At this point, I would like to give a list of the specifications for
  1326. commonly used CRC algorithms. However, most of the algorithms that I
  1327. have come into contact with so far are specified in such a vague way
  1328. that this has not been possible. What I can provide is a list of polys
  1329. for various CRC standards I have heard of:
  1330.  
  1331.    X25   standard : 1021       [CRC-CCITT, ADCCP, SDLC/HDLC]
  1332.    X25   reversed : 0811
  1333.  
  1334.    CRC16 standard : 8005
  1335.    CRC16 reversed : 4003       [LHA]
  1336.  
  1337.    CRC32          : 04C11DB7   [PKZIP, AUTODIN II, Ethernet, FDDI]
  1338.  
  1339. I would be interested in hearing from anyone out there who can tie
  1340. down the complete set of model parameters for any of these standards.
  1341.  
  1342. However, a program that was kicking around seemed to imply the
  1343. following specifications. Can anyone confirm or deny them (or provide
  1344. the check values (which I couldn't be bothered coding up and
  1345. calculating)).
  1346.  
  1347.    Name   : "CRC-16/CITT"
  1348.    Width  : 16
  1349.    Poly   : 1021
  1350.    Init   : FFFF
  1351.    RefIn  : False
  1352.    RefOut : False
  1353.    XorOut : 0000
  1354.    Check  : ?
  1355.  
  1356.  
  1357.    Name   : "XMODEM"
  1358.    Width  : 16
  1359.    Poly   : 8408
  1360.    Init   : 0000
  1361.    RefIn  : True
  1362.    RefOut : True
  1363.    XorOut : 0000
  1364.    Check  : ?
  1365.  
  1366.  
  1367.    Name   : "ARC"
  1368.    Width  : 16
  1369.    Poly   : 8005
  1370.    Init   : 0000
  1371.    RefIn  : True
  1372.    RefOut : True
  1373.    XorOut : 0000
  1374.    Check  : ?
  1375.  
  1376. Here is the specification for the CRC-32 algorithm which is reportedly
  1377. used in PKZip, AUTODIN II, Ethernet, and FDDI.
  1378.  
  1379.    Name   : "CRC-32"
  1380.    Width  : 32
  1381.    Poly   : 04C11DB7
  1382.    Init   : FFFFFFFF
  1383.    RefIn  : True
  1384.    RefOut : True
  1385.    XorOut : FFFFFFFF
  1386.    Check  : CBF43926
  1387.  
  1388.  
  1389. 17. An Implementation of the Model Algorithm
  1390. --------------------------------------------
  1391. Here is an implementation of the model algorithm in the C programming
  1392. language. The implementation consists of a header file (.h) and an
  1393. implementation file (.c). If you're reading this document in a
  1394. sequential scroller, you can skip this code by searching for the
  1395. string "Roll Your Own".
  1396.  
  1397. To ensure that the following code is working, configure it for the
  1398. CRC-16 and CRC-32 algorithms given above and ensure that they produce
  1399. the specified "check" checksum when fed the test string "123456789"
  1400. (see earlier).
  1401.  
  1402. /****************************************************************************/
  1403. /*                             Start of crcmodel.h                          */
  1404. /****************************************************************************/
  1405. /*                                                                          */
  1406. /* Author : Ross Williams (ross@guest.adelaide.edu.au.).                    */
  1407. /* Date   : 3 June 1993.                                                    */
  1408. /* Status : Public domain.                                                  */
  1409. /*                                                                          */
  1410. /* Description : This is the header (.h) file for the reference             */
  1411. /* implementation of the Rocksoft^tm Model CRC Algorithm. For more          */
  1412. /* information on the Rocksoft^tm Model CRC Algorithm, see the document     */
  1413. /* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross      */
  1414. /* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in */
  1415. /* "ftp.adelaide.edu.au/pub/rocksoft".                                      */
  1416. /*                                                                          */
  1417. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1418. /*                                                                          */
  1419. /****************************************************************************/
  1420. /*                                                                          */
  1421. /* How to Use This Package                                                  */
  1422. /* -----------------------                                                  */
  1423. /* Step 1: Declare a variable of type cm_t. Declare another variable        */
  1424. /*         (p_cm say) of type p_cm_t and initialize it to point to the first*/
  1425. /*         variable (e.g. p_cm_t p_cm = &cm_t).                             */
  1426. /*                                                                          */
  1427. /* Step 2: Assign values to the parameter fields of the structure.          */
  1428. /*         If you don't know what to assign, see the document cited earlier.*/
  1429. /*         For example:                                                     */
  1430. /*            p_cm->cm_width = 16;                                          */
  1431. /*            p_cm->cm_poly  = 0x8005L;                                     */
  1432. /*            p_cm->cm_init  = 0L;                                          */
  1433. /*            p_cm->cm_refin = TRUE;                                        */
  1434. /*            p_cm->cm_refot = TRUE;                                        */
  1435. /*            p_cm->cm_xorot = 0L;                                          */
  1436. /*         Note: Poly is specified without its top bit (18005 becomes 8005).*/
  1437. /*         Note: Width is one bit less than the raw poly width.             */
  1438. /*                                                                          */
  1439. /* Step 3: Initialize the instance with a call cm_ini(p_cm);                */
  1440. /*                                                                          */
  1441. /* Step 4: Process zero or more message bytes by placing zero or more       */
  1442. /*         successive calls to cm_nxt. Example: cm_nxt(p_cm,ch);            */
  1443. /*                                                                          */
  1444. /* Step 5: Extract the CRC value at any time by calling crc = cm_crc(p_cm); */
  1445. /*         If the CRC is a 16-bit value, it will be in the bottom 16 bits.  */
  1446. /*                                                                          */
  1447. /****************************************************************************/
  1448. /*                                                                          */
  1449. /* Design Notes                                                             */
  1450. /* ------------                                                             */
  1451. /* PORTABILITY: This package has been coded very conservatively so that     */
  1452. /* it will run on as many machines as possible. For example, all external   */
  1453. /* identifiers have been restricted to 6 characters and all internal ones to*/
  1454. /* 8 characters. The prefix cm (for Crc Model) is used as an attempt to     */
  1455. /* avoid namespace collisions. This package is endian independent.          */
  1456. /*                                                                          */
  1457. /* EFFICIENCY: This package (and its interface) is not designed for         */
  1458. /* speed. The purpose of this package is to act as a well-defined reference */
  1459. /* model for the specification of CRC algorithms. If you want speed, cook up*/
  1460. /* a specific table-driven implementation as described in the document cited*/
  1461. /* above. This package is designed for validation only; if you have found or*/
  1462. /* implemented a CRC algorithm and wish to describe it as a set of para-    */
  1463. /* meters to the Rocksoft^tm Model CRC Algorithm, your CRC algorithm imple- */
  1464. /* mentation should behave identically to this package under those para-    */
  1465. /* meters.                                                                  */
  1466. /*                                                                          */
  1467. /****************************************************************************/
  1468.  
  1469. /* The following #ifndef encloses this entire */
  1470. /* header file, rendering it idempotent.     */
  1471.  
  1472. #ifndef CM_DONE
  1473. #define CM_DONE
  1474.  
  1475. /****************************************************************************/
  1476. /* The following definitions are extracted from my style header file which  */
  1477. /* would be cumbersome to distribute with this package. The DONE_STYLE is   */
  1478. /* the idempotence symbol used in my style header file.                     */
  1479.  
  1480. #ifndef DONE_STYLE
  1481.  
  1482. typedef unsigned long   ulong;
  1483. typedef unsigned        bool;
  1484. typedef unsigned char * p_ubyte_;
  1485.  
  1486. #ifndef TRUE
  1487. #define FALSE 0
  1488. #define TRUE  1
  1489. #endif
  1490.  
  1491. /* Change to the second definition if you don't have prototypes. */
  1492. #define P_(A) A
  1493. /* #define P_(A) () */
  1494.  
  1495. /* Uncomment this definition if you don't have void. */
  1496. /* typedef int void; */
  1497.  
  1498. #endif
  1499.  
  1500. /****************************************************************************/
  1501. /* CRC Model Abstract Type                                                  */
  1502. /* -----------------------                                                  */
  1503. /* The following type stores the context of an executing instance of the    */
  1504. /* model algorithm. Most of the fields are model parameters which must be   */
  1505. /* set before the first initializing call to cm_ini.                        */
  1506.  
  1507. typedef struct
  1508.   {
  1509.    int   cm_width;   /* Parameter: Width in bits [8,32].       */
  1510.    ulong cm_poly;    /* Parameter: The algorithm's polynomial. */
  1511.    ulong cm_init;    /* Parameter: Initial register value.     */
  1512.    bool  cm_refin;   /* Parameter: Reflect input bytes?        */
  1513.    bool  cm_refot;   /* Parameter: Reflect output CRC?         */
  1514.    ulong cm_xorot;   /* Parameter: XOR this to output CRC.     */
  1515.  
  1516.    ulong cm_reg;     /* Context: Context during execution.     */
  1517.   } cm_t;
  1518. typedef cm_t *p_cm_t;
  1519.  
  1520. /****************************************************************************/
  1521. /* Functions That Implement The Model                                       */
  1522. /* ----------------------------------                                       */
  1523. /* The following functions animate the cm_t abstraction.                    */
  1524.  
  1525. void cm_ini P_((p_cm_t p_cm));
  1526.  
  1527. /* Initializes the argument CRC model instance.          */
  1528. /* All parameter fields must be set before calling this. */
  1529.  
  1530. void cm_nxt P_((p_cm_t p_cm,int ch));
  1531.  
  1532. /* Processes a single message byte [0,255]. */
  1533.  
  1534. void cm_blk P_((p_cm_t p_cm,p_ubyte_ blk_adr,ulong blk_len));
  1535.  
  1536. /* Processes a block of message bytes. */
  1537.  
  1538. ulong cm_crc P_((p_cm_t p_cm));
  1539.  
  1540. /* Returns the CRC value for the message bytes processed so far. */
  1541.  
  1542. /****************************************************************************/
  1543. /* Functions For Table Calculation                                          */
  1544. /* -------------------------------                                          */
  1545. /* The following function can be used to calculate a CRC lookup table.      */
  1546. /* It can also be used at run-time to create or check static tables.        */
  1547.  
  1548. ulong cm_tab P_((p_cm_t p_cm,int index));
  1549.  
  1550. /* Returns the i'th entry for the lookup table for the specified algorithm. */
  1551. /* The function examines the fields cm_width, cm_poly, cm_refin, and the    */
  1552. /* argument table index in the range [0,255] and returns the table entry in */
  1553. /* the bottom cm_width bytes of the return value. */
  1554.  
  1555. /****************************************************************************/
  1556. /* End of the header file idempotence #ifndef                               */
  1557.  
  1558. #endif
  1559.  
  1560. /****************************************************************************/
  1561. /*                             End of crcmodel.h                            */
  1562. /****************************************************************************/
  1563.  
  1564. /****************************************************************************/
  1565. /*                             Start of crcmodel.c                          */
  1566. /****************************************************************************/
  1567. /*                                                                          */
  1568. /* Author : Ross Williams (ross@guest.adelaide.edu.au.).                    */
  1569. /* Date   : 3 June 1993.                                                    */
  1570. /* Status : Public domain.                                                  */
  1571. /*                                                                          */
  1572. /* Description : This is the implementation (.c) file for the reference     */
  1573. /* implementation of the Rocksoft^tm Model CRC Algorithm. For more          */
  1574. /* information on the Rocksoft^tm Model CRC Algorithm, see the document     */
  1575. /* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross      */
  1576. /* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in */
  1577. /* "ftp.adelaide.edu.au/pub/rocksoft".                                      */
  1578. /*                                                                          */
  1579. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1580. /*                                                                          */
  1581. /****************************************************************************/
  1582. /*                                                                          */
  1583. /* Implementation Notes                                                     */
  1584. /* --------------------                                                     */
  1585. /* To avoid inconsistencies, the specification of each function is not      */
  1586. /* echoed here. See the header file for a description of these functions.   */
  1587. /* This package is light on checking because I want to keep it short and    */
  1588. /* simple and portable (i.e. it would be too messy to distribute my entire  */
  1589. /* C culture (e.g. assertions package) with this package.                   */
  1590. /*                                                                          */
  1591. /****************************************************************************/
  1592.  
  1593. #include "crcmodel.h"
  1594.  
  1595. /****************************************************************************/
  1596. /* The following definitions make the code more readable.                   */
  1597.  
  1598. #define BITMASK(X) (1L << (X))
  1599. #define MASK32 0xFFFFFFFFL
  1600. #define LOCAL static
  1601.  
  1602. /****************************************************************************/
  1603.  
  1604. LOCAL ulong reflect P_((ulong v,int b));
  1605. LOCAL ulong reflect (v,b)
  1606.  
  1607. /* Returns the value v with the bottom b [0,32] bits reflected. */
  1608. /* Example: reflect(0x3e23L,3) == 0x3e26                        */
  1609.  
  1610. ulong v;
  1611. int   b;
  1612. {
  1613.  int   i;
  1614.  ulong t = v;
  1615.  for (i=0; i<b; i++)
  1616.    {
  1617.     if (t & 1L)
  1618.        v|=  BITMASK((b-1)-i);
  1619.     else
  1620.        v&= ~BITMASK((b-1)-i);
  1621.  
  1622.     t>>=1;
  1623.  
  1624.    }
  1625.  return v;
  1626. }
  1627.  
  1628. /****************************************************************************/
  1629.  
  1630. LOCAL ulong widmask P_((p_cm_t));
  1631. LOCAL ulong widmask (p_cm)
  1632. /* Returns a longword whose value is (2^p_cm->cm_width)-1.     */
  1633. /* The trick is to do this portably (e.g. without doing <<32). */
  1634. p_cm_t p_cm;
  1635. {
  1636.  return (((1L<<(p_cm->cm_width-1))-1L)<<1)|1L;
  1637. }
  1638.  
  1639. /****************************************************************************/
  1640.  
  1641. void cm_ini (p_cm)
  1642. p_cm_t p_cm;
  1643. {
  1644.  p_cm->cm_reg = p_cm->cm_init;
  1645. }
  1646.  
  1647. /****************************************************************************/
  1648.  
  1649. void cm_nxt (p_cm,ch)
  1650. p_cm_t p_cm;
  1651. int    ch;
  1652. {
  1653.  int   i;
  1654.  ulong uch  = (ulong) ch;
  1655.  ulong topbit = BITMASK(p_cm->cm_width-1);
  1656.  
  1657.  if (p_cm->cm_refin) uch = reflect(uch,8);
  1658.  p_cm->cm_reg ^= (uch << (p_cm->cm_width-8));
  1659.  for (i=0; i<8; i++)
  1660.    {
  1661.     if (p_cm->cm_reg & topbit)
  1662.        p_cm->cm_reg = (p_cm->cm_reg << 1) ^ p_cm->cm_poly;
  1663.     else
  1664.        p_cm->cm_reg <<= 1;
  1665.     p_cm->cm_reg &= widmask(p_cm);
  1666.    }
  1667. }
  1668.  
  1669. /****************************************************************************/
  1670.  
  1671. void cm_blk (p_cm,blk_adr,blk_len)
  1672. p_cm_t   p_cm;
  1673. p_ubyte_ blk_adr;
  1674. ulong    blk_len;
  1675. {
  1676.  while (blk_len--) cm_nxt(p_cm,*blk_adr++);
  1677. }
  1678.  
  1679. /****************************************************************************/
  1680.  
  1681. ulong cm_crc (p_cm)
  1682. p_cm_t p_cm;
  1683. {
  1684.  if (p_cm->cm_refot)
  1685.     return p_cm->cm_xorot ^ reflect(p_cm->cm_reg,p_cm->cm_width);
  1686.  else
  1687.     return p_cm->cm_xorot ^ p_cm->cm_reg;
  1688. }
  1689.  
  1690. /****************************************************************************/
  1691.  
  1692. ulong cm_tab (p_cm,index)
  1693. p_cm_t p_cm;
  1694. int    index;
  1695. {
  1696.  int   i;
  1697.  ulong r;
  1698.  ulong topbit = BITMASK(p_cm->cm_width-1);
  1699.  ulong inbyte = (ulong) index;
  1700.  
  1701.  if (p_cm->cm_refin) inbyte = reflect(inbyte,8);
  1702.  r = inbyte << (p_cm->cm_width-8);
  1703.  for (i=0; i<8; i++)
  1704.     if (r & topbit)
  1705.        r = (r << 1) ^ p_cm->cm_poly;
  1706.     else
  1707.        r<<=1;
  1708.  if (p_cm->cm_refin) r = reflect(r,p_cm->cm_width);
  1709.  return r & widmask(p_cm);
  1710. }
  1711.  
  1712. /****************************************************************************/
  1713. /*                             End of crcmodel.c                            */
  1714. /****************************************************************************/
  1715.  
  1716.  
  1717. 18. Roll Your Own Table-Driven Implementation
  1718. ---------------------------------------------
  1719. Despite all the fuss I've made about understanding and defining CRC
  1720. algorithms, the mechanics of their high-speed implementation remains
  1721. trivial. There are really only two forms: normal and reflected. Normal
  1722. shifts to the left and covers the case of algorithms with Refin=FALSE
  1723. and Refot=FALSE. Reflected shifts to the right and covers algorithms
  1724. with both those parameters true. (If you want one parameter true and
  1725. the other false, you'll have to figure it out for yourself!) The
  1726. polynomial is embedded in the lookup table (to be discussed). The
  1727. other parameters, Init and XorOt can be coded as macros. Here is the
  1728. 32-bit normal form (the 16-bit form is similar).
  1729.  
  1730.    unsigned long crc_normal ();
  1731.    unsigned long crc_normal (blk_adr,blk_len)
  1732.    unsigned char *blk_adr;
  1733.    unsigned long  blk_len;
  1734.    {
  1735.     unsigned long crc = INIT;
  1736.     while (blk_len--)
  1737.        crc = crctable[((crc>>24) ^ *blk_adr++) & 0xFFL] ^ (crc << 8);
  1738.     return crc ^ XOROT;
  1739.    }
  1740.  
  1741. Here is the reflected form:
  1742.  
  1743.    unsigned long crc_reflected ();
  1744.    unsigned long crc_reflected (blk_adr,blk_len)
  1745.    unsigned char *blk_adr;
  1746.    unsigned long  blk_len;
  1747.    {
  1748.     unsigned long crc = INIT_REFLECTED;
  1749.     while (blk_len--)
  1750.        crc = crctable[(crc ^ *blk_adr++) & 0xFFL] ^ (crc >> 8));
  1751.     return crc ^ XOROT;
  1752.    }
  1753.  
  1754. Note: I have carefully checked the above two code fragments, but I
  1755. haven't actually compiled or tested them. This shouldn't matter to
  1756. you, as, no matter WHAT you code, you will always be able to tell if
  1757. you have got it right by running whatever you have created against the
  1758. reference model given earlier. The code fragments above are really
  1759. just a rough guide. The reference model is the definitive guide.
  1760.  
  1761. Note: If you don't care much about speed, just use the reference model
  1762. code!
  1763.  
  1764.  
  1765. 19. Generating A Lookup Table
  1766. -----------------------------
  1767. The only component missing from the normal and reversed code fragments
  1768. in the previous section is the lookup table. The lookup table can be
  1769. computed at run time using the cm_tab function of the model package
  1770. given earlier, or can be pre-computed and inserted into the C program.
  1771. In either case, it should be noted that the lookup table depends only
  1772. on the POLY and RefIn (and RefOt) parameters. Basically, the
  1773. polynomial determines the table, but you can generate a reflected
  1774. table too if you want to use the reflected form above.
  1775.  
  1776. The following program generates any desired 16-bit or 32-bit lookup
  1777. table. Skip to the word "Summary" if you want to skip over this code.
  1778.  
  1779.  
  1780.  
  1781. /****************************************************************************/
  1782. /*                             Start of crctable.c                          */
  1783. /****************************************************************************/
  1784. /*                                                                          */
  1785. /* Author  : Ross Williams (ross@guest.adelaide.edu.au.).                   */
  1786. /* Date    : 3 June 1993.                                                   */
  1787. /* Version : 1.0.                                                           */
  1788. /* Status  : Public domain.                                                 */
  1789. /*                                                                          */
  1790. /* Description : This program writes a CRC lookup table (suitable for       */
  1791. /* inclusion in a C program) to a designated output file. The program can be*/
  1792. /* statically configured to produce any table covered by the Rocksoft^tm    */
  1793. /* Model CRC Algorithm. For more information on the Rocksoft^tm Model CRC   */
  1794. /* Algorithm, see the document titled "A Painless Guide to CRC Error        */
  1795. /* Detection Algorithms" by Ross Williams (ross@guest.adelaide.edu.au.).    */
  1796. /* This document is likely to be in "ftp.adelaide.edu.au/pub/rocksoft".     */
  1797. /*                                                                          */
  1798. /* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.  */
  1799. /*                                                                          */
  1800. /****************************************************************************/
  1801.  
  1802. #include <stdio.h>
  1803. #include <stdlib.h>
  1804. #include "crcmodel.h"
  1805.  
  1806. /****************************************************************************/
  1807. /* TABLE PARAMETERS                                                         */
  1808. /* ================                                                         */
  1809. /* The following parameters entirely determine the table to be generated.   */
  1810. /* You should need to modify only the definitions in this section before    */
  1811. /* running this program.                                                    */
  1812. /*                                                                          */
  1813. /*    TB_FILE  is the name of the output file.                              */
  1814. /*    TB_WIDTH is the table width in bytes (either 2 or 4).                 */
  1815. /*    TB_POLY  is the "polynomial", which must be TB_WIDTH bytes wide.      */
  1816. /*    TB_REVER indicates whether the table is to be reversed (reflected).   */
  1817. /*                                                                          */
  1818. /* Example:                                                                 */
  1819. /*                                                                          */
  1820. /*    #define TB_FILE   "crctable.out"                                      */
  1821. /*    #define TB_WIDTH  2                                                   */
  1822. /*    #define TB_POLY   0x8005L                                             */
  1823. /*    #define TB_REVER  TRUE                                                */
  1824.  
  1825. #define TB_FILE   "crctable.out"
  1826. #define TB_WIDTH  4
  1827. #define TB_POLY   0x04C11DB7L
  1828. #define TB_REVER  TRUE
  1829.  
  1830. /****************************************************************************/
  1831. /* Miscellaneous definitions.                                               */
  1832.  
  1833. #define LOCAL static
  1834. FILE *outfile;
  1835. #define WR(X) fprintf(outfile,(X))
  1836. #define WP(X,Y) fprintf(outfile,(X),(Y))
  1837.  
  1838. /****************************************************************************/
  1839.  
  1840. LOCAL void chk_err P_((char *));
  1841. LOCAL void chk_err (mess)
  1842.  
  1843. /* If mess is non-empty, write it out and abort. Otherwise, check the error */
  1844. /* status of outfile and abort if an error has occurred.                    */
  1845.  
  1846. char *mess;
  1847. {
  1848.  if (mess[0] != 0   ) {printf("%s\n",mess); exit(EXIT_FAILURE);}
  1849.  if (ferror(outfile)) {perror("chk_err");   exit(EXIT_FAILURE);}
  1850. }
  1851.  
  1852. /****************************************************************************/
  1853.  
  1854. LOCAL void chkparam P_((void));
  1855. LOCAL void chkparam ()
  1856. {
  1857.  if ((TB_WIDTH != 2) && (TB_WIDTH != 4))
  1858.     chk_err("chkparam: Width parameter is illegal.");
  1859.  if ((TB_WIDTH == 2) && (TB_POLY & 0xFFFF0000L))
  1860.     chk_err("chkparam: Poly parameter is too wide.");
  1861.  if ((TB_REVER != FALSE) && (TB_REVER != TRUE))
  1862.     chk_err("chkparam: Reverse parameter is not boolean.");
  1863. }
  1864.  
  1865. /****************************************************************************/
  1866.  
  1867. LOCAL void gentable P_((void));
  1868. LOCAL void gentable ()
  1869. {
  1870.  WR("/*****************************************************************/\n");
  1871.  WR("/*                                                               */\n");
  1872.  WR("/* CRC LOOKUP TABLE                                              */\n");
  1873.  WR("/* ================                                              */\n");
  1874.  WR("/* The following CRC lookup table was generated automagically    */\n");
  1875.  WR("/* by the Rocksoft^tm Model CRC Algorithm Table Generation       */\n");
  1876.  WR("/* Program V1.0 using the following model parameters:            */\n");
  1877.  WR("/*                                                               */\n");
  1878.  WP("/*    Width   : %1lu bytes.                                         */\n",
  1879.  
  1880.     (ulong) TB_WIDTH);
  1881.  if (TB_WIDTH == 2)
  1882.  WP("/*    Poly    : 0x%04lX                                           */\n",
  1883.     (ulong) TB_POLY);
  1884.  else
  1885.  WP("/*    Poly    : 0x%08lXL                                      */\n",
  1886.     (ulong) TB_POLY);
  1887.  if (TB_REVER)
  1888.  WR("/*    Reverse : TRUE.                                            */\n");
  1889.  else
  1890.  WR("/*    Reverse : FALSE.                                           */\n");
  1891.  WR("/*                                                               */\n");
  1892.  WR("/* For more information on the Rocksoft^tm Model CRC Algorithm,  */\n");
  1893.  WR("/* see the document titled \"A Painless Guide to CRC Error        */\n");
  1894.  WR("/* Detection Algorithms\" by Ross Williams                        */\n");
  1895.  WR("/* (ross@guest.adelaide.edu.au.). This document is likely to be  */\n");
  1896.  WR("/* in the FTP archive \"ftp.adelaide.edu.au/pub/rocksoft\".        */\n");
  1897.  
  1898.  WR("/*                                                               */\n");
  1899.  WR("/*****************************************************************/\n");
  1900.  WR("\n");
  1901.  switch (TB_WIDTH)
  1902.    {
  1903.     case 2: WR("unsigned short crctable[256] =\n{\n"); break;
  1904.     case 4: WR("unsigned long  crctable[256] =\n{\n"); break;
  1905.     default: chk_err("gentable: TB_WIDTH is invalid.");
  1906.    }
  1907.  chk_err("");
  1908.  
  1909.  {
  1910.   int i;
  1911.   cm_t cm;
  1912.   char *form    = (TB_WIDTH==2) ? "0x%04lX" : "0x%08lXL";
  1913.   int   perline = (TB_WIDTH==2) ? 8 : 4;
  1914.  
  1915.   cm.cm_width = TB_WIDTH*8;
  1916.   cm.cm_poly  = TB_POLY;
  1917.   cm.cm_refin = TB_REVER;
  1918.  
  1919.   for (i=0; i<256; i++)
  1920.     {
  1921.      WR(" ");
  1922.      WP(form,(ulong) cm_tab(&cm,i));
  1923.      if (i != 255) WR(",");
  1924.      if (((i+1) % perline) == 0) WR("\n");
  1925.      chk_err("");
  1926.     }
  1927.  
  1928.  WR("};\n");
  1929.  WR("\n");
  1930.  WR("/*****************************************************************/\n");
  1931.  WR("/*                   End of CRC Lookup Table                     */\n");
  1932.  WR("/*****************************************************************/\n");
  1933.  WR("");
  1934.  chk_err("");
  1935. }
  1936. }
  1937.  
  1938. /****************************************************************************/
  1939.  
  1940. main ()
  1941. {
  1942.  printf("\n");
  1943.  printf("Rocksoft^tm Model CRC Algorithm Table Generation Program V1.0\n");
  1944.  printf("-------------------------------------------------------------\n");
  1945.  printf("Output file is \"%s\".\n",TB_FILE);
  1946.  chkparam();
  1947.  outfile = fopen(TB_FILE,"w"); chk_err("");
  1948.  gentable();
  1949.  if (fclose(outfile) != 0)
  1950.     chk_err("main: Couldn't close output file.");
  1951.  printf("\nSUCCESS: The table has been successfully written.\n");
  1952. }
  1953.  
  1954. /****************************************************************************/
  1955. /*                             End of crctable.c                            */
  1956. /****************************************************************************/
  1957.  
  1958. 20. Summary
  1959. -----------
  1960. This document has provided a detailed explanation of CRC algorithms
  1961. explaining their theory and stepping through increasingly
  1962. sophisticated implementations ranging from simple bit shifting through
  1963. to byte-at-a-time table-driven implementations. The various
  1964. implementations of different CRC algorithms that make them confusing
  1965. to deal with have been explained. A parameterized model algorithm has
  1966. been described that can be used to precisely define a particular CRC
  1967. algorithm, and a reference implementation provided. Finally, a program
  1968. to generate CRC tables has been provided.
  1969.  
  1970. 21. Corrections
  1971. ---------------
  1972. If you think that any part of this document is unclear or incorrect,
  1973. or have any other information, or suggestions on how this document
  1974. could be improved, please context the author. In particular, I would
  1975. like to hear from anyone who can provide Rocksoft^tm Model CRC
  1976. Algorithm parameters for standard algorithms out there.
  1977.  
  1978.  
  1979. A. Glossary
  1980. -----------
  1981. CHECKSUM - A number that has been calculated as a function of some
  1982. message. The literal interpretation of this word "Check-Sum" indicates
  1983. that the function should involve simply adding up the bytes in the
  1984. message. Perhaps this was what early checksums were. Today, however,
  1985. although more sophisticated formulae are used, the term "checksum" is
  1986. still used.
  1987.  
  1988. CRC - This stands for "Cyclic Redundancy Code". Whereas the term
  1989. "checksum" seems to be used to refer to any non-cryptographic checking
  1990. information unit, the term "CRC" seems to be reserved only for
  1991. algorithms that are based on the "polynomial" division idea.
  1992.  
  1993. G - This symbol is used in this document to represent the Poly.
  1994.  
  1995. MESSAGE - The input data being checksummed. This is usually structured
  1996. as a sequence of bytes. Whether the top bit or the bottom bit of each
  1997. byte is treated as the most significant or least significant is a
  1998. parameter of CRC algorithms.
  1999.  
  2000. POLY - This is my friendly term for the polynomial of a CRC.
  2001.  
  2002. POLYNOMIAL - The "polynomial" of a CRC algorithm is simply the divisor
  2003. in the division implementing the CRC algorithm.
  2004.  
  2005. REFLECT - A binary number is reflected by swapping all of its bits
  2006. around the central point. For example, 1101 is the reflection of 1011.
  2007.  
  2008. ROCKSOFT^TM MODEL CRC ALGORITHM - A parameterized algorithm whose
  2009. purpose is to act as a solid reference for describing CRC algorithms.
  2010. Typically CRC algorithms are specified by quoting a polynomial.
  2011. However, in order to construct a precise implementation, one also
  2012. needs to know initialization values and so on.
  2013.  
  2014. WIDTH - The width of a CRC algorithm is the width of its polynomial
  2015. minus one. For example, if the polynomial is 11010, the width would be
  2016. 4 bits. The width is usually set to be a multiple of 8 bits.
  2017.  
  2018.  
  2019. B. References
  2020. -------------
  2021. [Griffiths87] Griffiths, G., Carlyle Stones, G., "The Tea-Leaf Reader
  2022. Algorithm: An Efficient Implementation of CRC-16 and CRC-32",
  2023. Communications of the ACM, 30(7), pp.617-620. Comment: This paper
  2024. describes a high-speed table-driven implementation of CRC algorithms.
  2025. The technique seems to be a touch messy, and is superseded by the
  2026. Sarwate algorithm.
  2027.  
  2028. [Knuth81] Knuth, D.E., "The Art of Computer Programming", Volume 2:
  2029. Seminumerical Algorithms, Section 4.6.
  2030.  
  2031. [Nelson 91] Nelson, M., "The Data Compression Book", M&T Books, (501
  2032. Galveston Drive, Redwood City, CA 94063), 1991, ISBN: 1-55851-214-4.
  2033. Comment: If you want to see a real implementation of a real 32-bit
  2034. checksum algorithm, look on pages 440, and 446-448.
  2035.  
  2036. [Sarwate88] Sarwate, D.V., "Computation of Cyclic Redundancy Checks
  2037. via Table Look-Up", Communications of the ACM, 31(8), pp.1008-1013.
  2038. Comment: This paper describes a high-speed table-driven implementation
  2039. for CRC algorithms that is superior to the tea-leaf algorithm.
  2040. Although this paper describes the technique used by most modern CRC
  2041. implementations, I found the appendix of this paper (where all the
  2042. good stuff is) difficult to understand.
  2043.  
  2044. [Tanenbaum81] Tanenbaum, A.S., "Computer Networks", Prentice Hall,
  2045. 1981, ISBN: 0-13-164699-0. Comment: Section 3.5.3 on pages 128 to 132
  2046. provides a very clear description of CRC codes. However, it does not
  2047. describe table-driven implementation techniques.
  2048.  
  2049.  
  2050. C. References I Have Detected But Haven't Yet Sighted
  2051. -----------------------------------------------------
  2052. Boudreau, Steen, "Cyclic Redundancy Checking by Program," AFIPS
  2053. Proceedings, Vol. 39, 1971.
  2054.  
  2055. Davies, Barber, "Computer Networks and Their Protocols," J. Wiley &
  2056. Sons, 1979.
  2057.  
  2058. Higginson, Kirstein, "On the Computation of Cyclic Redundancy Checks
  2059. by Program," The Computer Journal (British), Vol. 16, No. 1, Feb 1973.
  2060.  
  2061. McNamara, J. E., "Technical Aspects of Data Communication," 2nd
  2062. Edition, Digital Press, Bedford, Massachusetts, 1982.
  2063.  
  2064. Marton and Frambs, "A Cyclic Redundancy Checking (CRC) Algorithm,"
  2065. Honeywell Computer Journal, Vol. 5, No. 3, 1971.
  2066.  
  2067. Nelson M., "File verification using CRC", Dr Dobbs Journal, May 1992,
  2068. pp.64-67.
  2069.  
  2070. Ramabadran T.V., Gaitonde S.S., "A tutorial on CRC computations", IEEE
  2071. Micro, Aug 1988.
  2072.  
  2073. Schwaderer W.D., "CRC Calculation", April 85 PC Tech Journal,
  2074. pp.118-133.
  2075.  
  2076. Ward R.K, Tabandeh M., "Error Correction and Detection, A Geometric
  2077. Approach" The Computer Journal, Vol. 27, No. 3, 1984, pp.246-253.
  2078.  
  2079. Wecker, S., "A Table-Lookup Algorithm for Software Computation of
  2080. Cyclic Redundancy Check (CRC)," Digital Equipment Corporation
  2081. memorandum, 1974.
  2082.  
  2083. ***** The END ******
  2084.