Project

General

Profile

crc_v3.txt

Greg Shah, 09/03/2014 12:59 PM

Download (87 KB)

 
1

    
2
A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS
3
==================================================
4
"Everything you wanted to know about CRC algorithms, but were afraid
5
to ask for fear that errors in your understanding might be detected."
6

    
7
Version : 3.
8
Date    : 19 August 1993.
9
Author  : Ross N. Williams.
10
Net     : ross@guest.adelaide.edu.au.
11
FTP     : ftp.adelaide.edu.au/pub/rocksoft/crc_v3.txt
12
Company : Rocksoft^tm Pty Ltd.
13
Snail   : 16 Lerwick Avenue, Hazelwood Park 5066, Australia.
14
Fax     : +61 8 373-4911 (c/- Internode Systems Pty Ltd).
15
Phone   : +61 8 379-9217 (10am to 10pm Adelaide Australia time).
16
Note    : "Rocksoft" is a trademark of Rocksoft Pty Ltd, Australia.
17
Status  : Copyright (C) Ross Williams, 1993. However, permission is
18
          granted to make and distribute verbatim copies of this
19
          document provided that this information block and copyright
20
          notice is included. Also, the C code modules included
21
          in this document are fully public domain.
22
Thanks  : Thanks to Jean-loup Gailly (jloup@chorus.fr) and Mark Adler
23
          (me@quest.jpl.nasa.gov) who both proof read this document
24
          and picked out lots of nits as well as some big fat bugs.
25

    
26
Table of Contents
27
-----------------
28
    Abstract
29
 1. Introduction: Error Detection
30
 2. The Need For Complexity
31
 3. The Basic Idea Behind CRC Algorithms
32
 4. Polynomical Arithmetic
33
 5. Binary Arithmetic with No Carries
34
 6. A Fully Worked Example
35
 7. Choosing A Poly
36
 8. A Straightforward CRC Implementation
37
 9. A Table-Driven Implementation
38
10. A Slightly Mangled Table-Driven Implementation
39
11. "Reflected" Table-Driven Implementations
40
12. "Reversed" Polys
41
13. Initial and Final Values
42
14. Defining Algorithms Absolutely
43
15. A Parameterized Model For CRC Algorithms
44
16. A Catalog of Parameter Sets for Standards
45
17. An Implementation of the Model Algorithm
46
18. Roll Your Own Table-Driven Implementation
47
19. Generating A Lookup Table
48
20. Summary
49
21. Corrections
50
 A. Glossary
51
 B. References
52
 C. References I Have Detected But Haven't Yet Sighted
53

    
54

    
55
Abstract
56
--------
57
This document explains CRCs (Cyclic Redundancy Codes) and their
58
table-driven implementations in full, precise detail. Much of the
59
literature on CRCs, and in particular on their table-driven
60
implementations, is a little obscure (or at least seems so to me).
61
This document is an attempt to provide a clear and simple no-nonsense
62
explanation of CRCs and to absolutely nail down every detail of the
63
operation of their high-speed implementations. In addition to this,
64
this document presents a parameterized model CRC algorithm called the
65
"Rocksoft^tm Model CRC Algorithm". The model algorithm can be
66
parameterized to behave like most of the CRC implementations around,
67
and so acts as a good reference for describing particular algorithms.
68
A low-speed implementation of the model CRC algorithm is provided in
69
the C programming language. Lastly there is a section giving two forms
70
of high-speed table driven implementations, and providing a program
71
that generates CRC lookup tables.
72

    
73

    
74
1. Introduction: Error Detection
75
--------------------------------
76
The aim of an error detection technique is to enable the receiver of a
77
message transmitted through a noisy (error-introducing) channel to
78
determine whether the message has been corrupted. To do this, the
79
transmitter constructs a value (called a checksum) that is a function
80
of the message, and appends it to the message. The receiver can then
81
use the same function to calculate the checksum of the received
82
message and compare it with the appended checksum to see if the
83
message was correctly received. For example, if we chose a checksum
84
function which was simply the sum of the bytes in the message mod 256
85
(i.e. modulo 256), then it might go something as follows. All numbers
86
are in decimal.
87

    
88
   Message                    :  6 23  4
89
   Message with checksum      :  6 23  4 33
90
   Message after transmission :  6 27  4 33
91

    
92
In the above, the second byte of the message was corrupted from 23 to
93
27 by the communications channel. However, the receiver can detect
94
this by comparing the transmitted checksum (33) with the computer
95
checksum of 37 (6 + 27 + 4). If the checksum itself is corrupted, a
96
correctly transmitted message might be incorrectly identified as a
97
corrupted one. However, this is a safe-side failure. A dangerous-side
98
failure occurs where the message and/or checksum is corrupted in a
99
manner that results in a transmission that is internally consistent.
100
Unfortunately, this possibility is completely unavoidable and the best
101
that can be done is to minimize its probability by increasing the
102
amount of information in the checksum (e.g. widening the checksum from
103
one byte to two bytes).
104

    
105
Other error detection techniques exist that involve performing complex
106
transformations on the message to inject it with redundant
107
information. However, this document addresses only CRC algorithms,
108
which fall into the class of error detection algorithms that leave the
109
data intact and append a checksum on the end. i.e.:
110

    
111
      <original intact message> <checksum>
112

    
113

    
114
2. The Need For Complexity
115
--------------------------
116
In the checksum example in the previous section, we saw how a
117
corrupted message was detected using a checksum algorithm that simply
118
sums the bytes in the message mod 256:
119

    
120
   Message                    :  6 23  4
121
   Message with checksum      :  6 23  4 33
122
   Message after transmission :  6 27  4 33
123

    
124
A problem with this algorithm is that it is too simple. If a number of
125
random corruptions occur, there is a 1 in 256 chance that they will
126
not be detected. For example:
127

    
128
   Message                    :  6 23  4
129
   Message with checksum      :  6 23  4 33
130
   Message after transmission :  8 20  5 33
131

    
132
To strengthen the checksum, we could change from an 8-bit register to
133
a 16-bit register (i.e. sum the bytes mod 65536 instead of mod 256) so
134
as to apparently reduce the probability of failure from 1/256 to
135
1/65536. While basically a good idea, it fails in this case because
136
the formula used is not sufficiently "random"; with a simple summing
137
formula, each incoming byte affects roughly only one byte of the
138
summing register no matter how wide it is. For example, in the second
139
example above, the summing register could be a Megabyte wide, and the
140
error would still go undetected. This problem can only be solved by
141
replacing the simple summing formula with a more sophisticated formula
142
that causes each incoming byte to have an effect on the entire
143
checksum register.
144

    
145
Thus, we see that at least two aspects are required to form a strong
146
checksum function:
147

    
148
   WIDTH: A register width wide enough to provide a low a-priori
149
          probability of failure (e.g. 32-bits gives a 1/2^32 chance
150
          of failure).
151

    
152
   CHAOS: A formula that gives each input byte the potential to change
153
          any number of bits in the register.
154

    
155
Note: The term "checksum" was presumably used to describe early
156
summing formulas, but has now taken on a more general meaning
157
encompassing more sophisticated algorithms such as the CRC ones. The
158
CRC algorithms to be described satisfy the second condition very well,
159
and can be configured to operate with a variety of checksum widths.
160

    
161

    
162
3. The Basic Idea Behind CRC Algorithms
163
---------------------------------------
164
Where might we go in our search for a more complex function than
165
summing? All sorts of schemes spring to mind. We could construct
166
tables using the digits of pi, or hash each incoming byte with all the
167
bytes in the register. We could even keep a large telephone book
168
on-line, and use each incoming byte combined with the register bytes
169
to index a new phone number which would be the next register value.
170
The possibilities are limitless.
171

    
172
However, we do not need to go so far; the next arithmetic step
173
suffices. While addition is clearly not strong enough to form an
174
effective checksum, it turns out that division is, so long as the
175
divisor is about as wide as the checksum register.
176

    
177
The basic idea of CRC algorithms is simply to treat the message as an
178
enormous binary number, to divide it by another fixed binary number,
179
and to make the remainder from this division the checksum. Upon
180
receipt of the message, the receiver can perform the same division and
181
compare the remainder with the "checksum" (transmitted remainder).
182

    
183
Example: Suppose the the message consisted of the two bytes (6,23) as
184
in the previous example. These can be considered to be the hexadecimal
185
number 0617 which can be considered to be the binary number
186
0000-0110-0001-0111. Suppose that we use a checksum register one-byte
187
wide and use a constant divisor of 1001, then the checksum is the
188
remainder after 0000-0110-0001-0111 is divided by 1001. While in this
189
case, this calculation could obviously be performed using common
190
garden variety 32-bit registers, in the general case this is messy. So
191
instead, we'll do the division using good-'ol long division which you
192
learnt in school (remember?). Except this time, it's in binary:
193

    
194
          ...0000010101101 = 00AD =  173 = QUOTIENT
195
         ____-___-___-___-
196
9= 1001 ) 0000011000010111 = 0617 = 1559 = DIVIDEND
197
DIVISOR   0000.,,....,.,,,
198
          ----.,,....,.,,,
199
           0000,,....,.,,,
200
           0000,,....,.,,,
201
           ----,,....,.,,,
202
            0001,....,.,,,
203
            0000,....,.,,,
204
            ----,....,.,,,
205
             0011....,.,,,
206
             0000....,.,,,
207
             ----....,.,,,
208
              0110...,.,,,
209
              0000...,.,,,
210
              ----...,.,,,
211
               1100..,.,,,
212
               1001..,.,,,
213
               ====..,.,,,
214
                0110.,.,,,
215
                0000.,.,,,
216
                ----.,.,,,
217
                 1100,.,,,
218
                 1001,.,,,
219
                 ====,.,,,
220
                  0111.,,,
221
                  0000.,,,
222
                  ----.,,,
223
                   1110,,,
224
                   1001,,,
225
                   ====,,,
226
                    1011,,
227
                    1001,,
228
                    ====,,
229
                     0101,
230
                     0000,
231
                     ----
232
                      1011
233
                      1001
234
                      ====
235
                      0010 = 02 = 2 = REMAINDER
236

    
237

    
238
In decimal this is "1559 divided by 9 is 173 with a remainder of 2".
239

    
240
Although the effect of each bit of the input message on the quotient
241
is not all that significant, the 4-bit remainder gets kicked about
242
quite a lot during the calculation, and if more bytes were added to
243
the message (dividend) it's value could change radically again very
244
quickly. This is why division works where addition doesn't.
245

    
246
In case you're wondering, using this 4-bit checksum the transmitted
247
message would look like this (in hexadecimal): 06172 (where the 0617
248
is the message and the 2 is the checksum). The receiver would divide
249
0617 by 9 and see whether the remainder was 2.
250

    
251

    
252
4. Polynomical Arithmetic
253
-------------------------
254
While the division scheme described in the previous section is very
255
very similar to the checksumming schemes called CRC schemes, the CRC
256
schemes are in fact a bit weirder, and we need to delve into some
257
strange number systems to understand them.
258

    
259
The word you will hear all the time when dealing with CRC algorithms
260
is the word "polynomial". A given CRC algorithm will be said to be
261
using a particular polynomial, and CRC algorithms in general are said
262
to be operating using polynomial arithmetic. What does this mean?
263

    
264
Instead of the divisor, dividend (message), quotient, and remainder
265
(as described in the previous section) being viewed as positive
266
integers, they are viewed as polynomials with binary coefficients.
267
This is done by treating each number as a bit-string whose bits are
268
the coefficients of a polynomial. For example, the ordinary number 23
269
(decimal) is 17 (hex) and 10111 binary and so it corresponds to the
270
polynomial:
271

    
272
   1*x^4 + 0*x^3 + 1*x^2 + 1*x^1 + 1*x^0
273

    
274
or, more simply:
275

    
276
   x^4 + x^2 + x^1 + x^0
277

    
278
Using this technique, the message, and the divisor can be represented
279
as polynomials and we can do all our arithmetic just as before, except
280
that now it's all cluttered up with Xs. For example, suppose we wanted
281
to multiply 1101 by 1011. We can do this simply by multiplying the
282
polynomials:
283

    
284
(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
285
= (x^6 + x^4 + x^3
286
 + x^5 + x^3 + x^2
287
 + x^3 + x^1 + x^0) = x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
288

    
289
At this point, to get the right answer, we have to pretend that x is 2
290
and propagate binary carries from the 3*x^3 yielding
291

    
292
   x^7 + x^3 + x^2 + x^1 + x^0
293

    
294
It's just like ordinary arithmetic except that the base is abstracted
295
and brought into all the calculations explicitly instead of being
296
there implicitly. So what's the point?
297

    
298
The point is that IF we pretend that we DON'T know what x is, we CAN'T
299
perform the carries. We don't know that 3*x^3 is the same as x^4 + x^3
300
because we don't know that x is 2. In this true polynomial arithmetic
301
the relationship between all the coefficients is unknown and so the
302
coefficients of each power effectively become strongly typed;
303
coefficients of x^2 are effectively of a different type to
304
coefficients of x^3.
305

    
306
With the coefficients of each power nicely isolated, mathematicians
307
came up with all sorts of different kinds of polynomial arithmetics
308
simply by changing the rules about how coefficients work. Of these
309
schemes, one in particular is relevant here, and that is a polynomial
310
arithmetic where the coefficients are calculated MOD 2 and there is no
311
carry; all coefficients must be either 0 or 1 and no carries are
312
calculated. This is called "polynomial arithmetic mod 2". Thus,
313
returning to the earlier example:
314

    
315
(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
316
= (x^6 + x^4 + x^3
317
 + x^5 + x^3 + x^2
318
 + x^3 + x^1 + x^0)
319
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0
320

    
321
Under the other arithmetic, the 3*x^3 term was propagated using the
322
carry mechanism using the knowledge that x=2. Under "polynomial
323
arithmetic mod 2", we don't know what x is, there are no carries, and
324
all coefficients have to be calculated mod 2. Thus, the result
325
becomes:
326

    
327
= x^6 + x^5 + x^4 + x^3 + x^2 + x^1 + x^0
328

    
329
As Knuth [Knuth81] says (p.400):
330

    
331
   "The reader should note the similarity between polynomial
332
   arithmetic and multiple-precision arithmetic (Section 4.3.1), where
333
   the radix b is substituted for x. The chief difference is that the
334
   coefficient u_k of x^k in polynomial arithmetic bears little or no
335
   relation to its neighboring coefficients x^{k-1} [and x^{k+1}], so
336
   the idea of "carrying" from one place to another is absent. In fact
337
   polynomial arithmetic modulo b is essentially identical to multiple
338
   precision arithmetic with radix b, except that all carries are
339
   suppressed."
340

    
341
Thus polynomical arithmetic mod 2 is just binary arithmetic mod 2 with
342
no carries. While polynomials provide useful mathematical machinery in
343
more analytical approaches to CRC and error-correction algorithms, for
344
the purposes of exposition they provide no extra insight and some
345
encumbrance and have been discarded in the remainder of this document
346
in favour of direct manipulation of the arithmetical system with which
347
they are isomorphic: binary arithmetic with no carry.
348

    
349

    
350
5. Binary Arithmetic with No Carries
351
------------------------------------
352
Having dispensed with polynomials, we can focus on the real arithmetic
353
issue, which is that all the arithmetic performed during CRC
354
calculations is performed in binary with no carries. Often this is
355
called polynomial arithmetic, but as I have declared the rest of this
356
document a polynomial free zone, we'll have to call it CRC arithmetic
357
instead. As this arithmetic is a key part of CRC calculations, we'd
358
better get used to it. Here we go:
359

    
360
Adding two numbers in CRC arithmetic is the same as adding numbers in
361
ordinary binary arithmetic except there is no carry. This means that
362
each pair of corresponding bits determine the corresponding output bit
363
without reference to any other bit positions. For example:
364

    
365
        10011011
366
       +11001010
367
        --------
368
        01010001
369
        --------
370

    
371
There are only four cases for each bit position:
372

    
373
   0+0=0
374
   0+1=1
375
   1+0=1
376
   1+1=0  (no carry)
377

    
378
Subtraction is identical:
379

    
380
        10011011
381
       -11001010
382
        --------
383
        01010001
384
        --------
385

    
386
with
387

    
388
   0-0=0
389
   0-1=1  (wraparound)
390
   1-0=1
391
   1-1=0
392

    
393
In fact, both addition and subtraction in CRC arithmetic is equivalent
394
to the XOR operation, and the XOR operation is its own inverse. This
395
effectively reduces the operations of the first level of power
396
(addition, subtraction) to a single operation that is its own inverse.
397
This is a very convenient property of the arithmetic.
398

    
399
By collapsing of addition and subtraction, the arithmetic discards any
400
notion of magnitude beyond the power of its highest one bit. While it
401
seems clear that 1010 is greater than 10, it is no longer the case
402
that 1010 can be considered to be greater than 1001. To see this, note
403
that you can get from 1010 to 1001 by both adding and subtracting the
404
same quantity:
405

    
406
   1010 = 1010 + 0011
407
   1010 = 1010 - 0011
408

    
409
This makes nonsense of any notion of order.
410

    
411
Having defined addition, we can move to multiplication and division.
412
Multiplication is absolutely straightforward, being the sum of the
413
first number, shifted in accordance with the second number.
414

    
415
        1101
416
      x 1011
417
        ----
418
        1101
419
       1101.
420
      0000..
421
     1101...
422
     -------
423
     1111111  Note: The sum uses CRC addition
424
     -------
425

    
426
Division is a little messier as we need to know when "a number goes
427
into another number". To do this, we invoke the weak definition of
428
magnitude defined earlier: that X is greater than or equal to Y iff
429
the position of the highest 1 bit of X is the same or greater than the
430
position of the highest 1 bit of Y. Here's a fully worked division
431
(nicked from [Tanenbaum81]).
432

    
433
            1100001010
434
       _______________
435
10011 ) 11010110110000
436
        10011,,.,,....
437
        -----,,.,,....
438
         10011,.,,....
439
         10011,.,,....
440
         -----,.,,....
441
          00001.,,....
442
          00000.,,....
443
          -----.,,....
444
           00010,,....
445
           00000,,....
446
           -----,,....
447
            00101,....
448
            00000,....
449
            -----,....
450
             01011....
451
             00000....
452
             -----....
453
              10110...
454
              10011...
455
              -----...
456
               01010..
457
               00000..
458
               -----..
459
                10100.
460
                10011.
461
                -----.
462
                 01110
463
                 00000
464
                 -----
465
                  1110 = Remainder
466

    
467
That's really it. Before proceeding further, however, it's worth our
468
while playing with this arithmetic a bit to get used to it.
469

    
470
We've already played with addition and subtraction, noticing that they
471
are the same thing. Here, though, we should note that in this
472
arithmetic A+0=A and A-0=A. This obvious property is very useful
473
later.
474

    
475
In dealing with CRC multiplication and division, it's worth getting a
476
feel for the concepts of MULTIPLE and DIVISIBLE.
477

    
478
If a number A is a multiple of B then what this means in CRC
479
arithmetic is that it is possible to construct A from zero by XORing
480
in various shifts of B. For example, if A was 0111010110 and B was 11,
481
we could construct A from B as follows:
482

    
483
                  0111010110
484
                = .......11.
485
                + ....11....
486
                + ...11.....
487
                  .11.......
488

    
489
However, if A is 0111010111, it is not possible to construct it out of
490
various shifts of B (can you see why? - see later) so it is said to be
491
not divisible by B in CRC arithmetic.
492

    
493
Thus we see that CRC arithmetic is primarily about XORing particular
494
values at various shifting offsets.
495

    
496

    
497
6. A Fully Worked Example
498
-------------------------
499
Having defined CRC arithmetic, we can now frame a CRC calculation as
500
simply a division, because that's all it is! This section fills in the
501
details and gives an example.
502

    
503
To perform a CRC calculation, we need to choose a divisor. In maths
504
marketing speak the divisor is called the "generator polynomial" or
505
simply the "polynomial", and is a key parameter of any CRC algorithm.
506
It would probably be more friendly to call the divisor something else,
507
but the poly talk is so deeply ingrained in the field that it would
508
now be confusing to avoid it. As a compromise, we will refer to the
509
CRC polynomial as the "poly". Just think of this number as a sort of
510
parrot. "Hello poly!"
511

    
512
You can choose any poly and come up with a CRC algorithm. However,
513
some polys are better than others, and so it is wise to stick with the
514
tried an tested ones. A later section addresses this issue.
515

    
516
The width (position of the highest 1 bit) of the poly is very
517
important as it dominates the whole calculation. Typically, widths of
518
16 or 32 are chosen so as to simplify implementation on modern
519
computers. The width of a poly is the actual bit position of the
520
highest bit. For example, the width of 10011 is 4, not 5. For the
521
purposes of example, we will chose a poly of 10011 (of width W of 4).
522

    
523
Having chosen a poly, we can proceed with the calculation. This is
524
simply a division (in CRC arithmetic) of the message by the poly. The
525
only trick is that W zero bits are appended to the message before the
526
CRC is calculated. Thus we have:
527

    
528
   Original message                : 1101011011
529
   Poly                            :      10011
530
   Message after appending W zeros : 11010110110000
531

    
532
Now we simply divide the augmented message by the poly using CRC
533
arithmetic. This is the same division as before:
534

    
535
            1100001010 = Quotient (nobody cares about the quotient)
536
       _______________
537
10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
538
=Poly  10011,,.,,....
539
        -----,,.,,....
540
         10011,.,,....
541
         10011,.,,....
542
         -----,.,,....
543
          00001.,,....
544
          00000.,,....
545
          -----.,,....
546
           00010,,....
547
           00000,,....
548
           -----,,....
549
            00101,....
550
            00000,....
551
            -----,....
552
             01011....
553
             00000....
554
             -----....
555
              10110...
556
              10011...
557
              -----...
558
               01010..
559
               00000..
560
               -----..
561
                10100.
562
                10011.
563
                -----.
564
                 01110
565
                 00000
566
                 -----
567
                  1110 = Remainder = THE CHECKSUM!!!!
568

    
569
The division yields a quotient, which we throw away, and a remainder,
570
which is the calculated checksum. This ends the calculation.
571

    
572
Usually, the checksum is then appended to the message and the result
573
transmitted. In this case the transmission would be: 11010110111110.
574

    
575
At the other end, the receiver can do one of two things:
576

    
577
   a. Separate the message and checksum. Calculate the checksum for
578
      the message (after appending W zeros) and compare the two
579
      checksums.
580

    
581
   b. Checksum the whole lot (without appending zeros) and see if it
582
      comes out as zero!
583

    
584
These two options are equivalent. However, in the next section, we
585
will be assuming option b because it is marginally mathematically
586
cleaner.
587

    
588
A summary of the operation of the class of CRC algorithms:
589

    
590
   1. Choose a width W, and a poly G (of width W).
591
   2. Append W zero bits to the message. Call this M'.
592
   3. Divide M' by G using CRC arithmetic. The remainder is the checksum.
593

    
594
That's all there is to it.
595

    
596
7. Choosing A Poly
597
------------------
598
Choosing a poly is somewhat of a black art and the reader is referred
599
to [Tanenbaum81] (p.130-132) which has a very clear discussion of this
600
issue. This section merely aims to put the fear of death into anyone
601
who so much as toys with the idea of making up their own poly. If you
602
don't care about why one poly might be better than another and just
603
want to find out about high-speed implementations, choose one of the
604
arithmetically sound polys listed at the end of this section and skip
605
to the next section.
606

    
607
First note that the transmitted message T is a multiple of the poly.
608
To see this, note that 1) the last W bits of T is the remainder after
609
dividing the augmented (by zeros remember) message by the poly, and 2)
610
addition is the same as subtraction so adding the remainder pushes the
611
value up to the next multiple. Now note that if the transmitted
612
message is corrupted in transmission that we will receive T+E where E
613
is an error vector (and + is CRC addition (i.e. XOR)). Upon receipt of
614
this message, the receiver divides T+E by G. As T mod G is 0, (T+E)
615
mod G = E mod G. Thus, the capacity of the poly we choose to catch
616
particular kinds of errors will be determined by the set of multiples
617
of G, for any corruption E that is a multiple of G will be undetected.
618
Our task then is to find classes of G whose multiples look as little
619
like the kind of line noise (that will be creating the corruptions) as
620
possible. So let's examine the kinds of line noise we can expect.
621

    
622
SINGLE BIT ERRORS: A single bit error means E=1000...0000. We can
623
ensure that this class of error is always detected by making sure that
624
G has at least two bits set to 1. Any multiple of G will be
625
constructed using shifting and adding and it is impossible to
626
construct a value with a single bit by shifting an adding a single
627
value with more than one bit set, as the two end bits will always
628
persist.
629

    
630
TWO-BIT ERRORS: To detect all errors of the form 100...000100...000
631
(i.e. E contains two 1 bits) choose a G that does not have multiples
632
that are 11, 101, 1001, 10001, 100001, etc. It is not clear to me how
633
one goes about doing this (I don't have the pure maths background),
634
but Tanenbaum assures us that such G do exist, and cites G with 1 bits
635
(15,14,1) turned on as an example of one G that won't divide anything
636
less than 1...1 where ... is 32767 zeros.
637

    
638
ERRORS WITH AN ODD NUMBER OF BITS: We can catch all corruptions where
639
E has an odd number of bits by choosing a G that has an even number of
640
bits. To see this, note that 1) CRC multiplication is simply XORing a
641
constant value into a register at various offsets, 2) XORing is simply
642
a bit-flip operation, and 3) if you XOR a value with an even number of
643
bits into a register, the oddness of the number of 1 bits in the
644
register remains invariant. Example: Starting with E=111, attempt to
645
flip all three bits to zero by the repeated application of XORing in
646
11 at one of the two offsets (i.e. "E=E XOR 011" and "E=E XOR 110")
647
This is nearly isomorphic to the "glass tumblers" party puzzle where
648
you challenge someone to flip three tumblers by the repeated
649
application of the operation of flipping any two. Most of the popular
650
CRC polys contain an even number of 1 bits. (Note: Tanenbaum states
651
more specifically that all errors with an odd number of bits can be
652
caught by making G a multiple of 11).
653

    
654
BURST ERRORS: A burst error looks like E=000...000111...11110000...00.
655
That is, E consists of all zeros except for a run of 1s somewhere
656
inside. This can be recast as E=(10000...00)(1111111...111) where
657
there are z zeros in the LEFT part and n ones in the RIGHT part. To
658
catch errors of this kind, we simply set the lowest bit of G to 1.
659
Doing this ensures that LEFT cannot be a factor of G. Then, so long as
660
G is wider than RIGHT, the error will be detected. See Tanenbaum for a
661
clearer explanation of this; I'm a little fuzzy on this one. Note:
662
Tanenbaum asserts that the probability of a burst of length greater
663
than W getting through is (0.5)^W.
664

    
665
That concludes the section on the fine art of selecting polys.
666

    
667
Some popular polys are:
668
16 bits: (16,12,5,0)                                [X25 standard]
669
         (16,15,2,0)                                ["CRC-16"]
670
32 bits: (32,26,23,22,16,12,11,10,8,7,5,4,2,1,0)    [Ethernet]
671

    
672

    
673
8. A Straightforward CRC Implementation
674
---------------------------------------
675
That's the end of the theory; now we turn to implementations. To start
676
with, we examine an absolutely straight-down-the-middle boring
677
straightforward low-speed implementation that doesn't use any speed
678
tricks at all. We'll then transform that program progessively until we
679
end up with the compact table-driven code we all know and love and
680
which some of us would like to understand.
681

    
682
To implement a CRC algorithm all we have to do is implement CRC
683
division. There are two reasons why we cannot simply use the divide
684
instruction of whatever machine we are on. The first is that we have
685
to do the divide in CRC arithmetic. The second is that the dividend
686
might be ten megabytes long, and todays processors do not have
687
registers that big.
688

    
689
So to implement CRC division, we have to feed the message through a
690
division register. At this point, we have to be absolutely precise
691
about the message data. In all the following examples the message will
692
be considered to be a stream of bytes (each of 8 bits) with bit 7 of
693
each byte being considered to be the most significant bit (MSB). The
694
bit stream formed from these bytes will be the bit stream with the MSB
695
(bit 7) of the first byte first, going down to bit 0 of the first
696
byte, and then the MSB of the second byte and so on.
697

    
698
With this in mind, we can sketch an implementation of the CRC
699
division. For the purposes of example, consider a poly with W=4 and
700
the poly=10111. Then, the perform the division, we need to use a 4-bit
701
register:
702

    
703
                  3   2   1   0   Bits
704
                +---+---+---+---+
705
       Pop! <-- |   |   |   |   | <----- Augmented message
706
                +---+---+---+---+
707

    
708
             1    0   1   1   1   = The Poly
709

    
710
(Reminder: The augmented message is the message followed by W zero bits.)
711

    
712
To perform the division perform the following:
713

    
714
   Load the register with zero bits.
715
   Augment the message by appending W zero bits to the end of it.
716
   While (more message bits)
717
      Begin
718
      Shift the register left by one bit, reading the next bit of the
719
         augmented message into register bit position 0.
720
      If (a 1 bit popped out of the register during step 3)
721
         Register = Register XOR Poly.
722
      End
723
   The register now contains the remainder.
724

    
725
(Note: In practice, the IF condition can be tested by testing the top
726
 bit of R before performing the shift.)
727

    
728
We will call this algorithm "SIMPLE".
729

    
730
This might look a bit messy, but all we are really doing is
731
"subtracting" various powers (i.e. shiftings) of the poly from the
732
message until there is nothing left but the remainder. Study the
733
manual examples of long division if you don't understand this.
734

    
735
It should be clear that the above algorithm will work for any width W.
736

    
737

    
738
9. A Table-Driven Implementation
739
--------------------------------
740
The SIMPLE algorithm above is a good starting point because it
741
corresponds directly to the theory presented so far, and because it is
742
so SIMPLE. However, because it operates at the bit level, it is rather
743
awkward to code (even in C), and inefficient to execute (it has to
744
loop once for each bit). To speed it up, we need to find a way to
745
enable the algorithm to process the message in units larger than one
746
bit. Candidate quantities are nibbles (4 bits), bytes (8 bits), words
747
(16 bits) and longwords (32 bits) and higher if we can achieve it. Of
748
these, 4 bits is best avoided because it does not correspond to a byte
749
boundary. At the very least, any speedup should allow us to operate at
750
byte boundaries, and in fact most of the table driven algorithms
751
operate a byte at a time.
752

    
753
For the purposes of discussion, let us switch from a 4-bit poly to a
754
32-bit one. Our register looks much the same, except the boxes
755
represent bytes instead of bits, and the Poly is 33 bits (one implicit
756
1 bit at the top and 32 "active" bits) (W=32).
757

    
758
                   3    2    1    0   Bytes
759
                +----+----+----+----+
760
       Pop! <-- |    |    |    |    | <----- Augmented message
761
                +----+----+----+----+
762

    
763
               1<------32 bits------>
764

    
765
The SIMPLE algorithm is still applicable. Let us examine what it does.
766
Imagine that the SIMPLE algorithm is in full swing and consider the
767
top 8 bits of the 32-bit register (byte 3) to have the values:
768

    
769
   t7 t6 t5 t4 t3 t2 t1 t0
770

    
771
In the next iteration of SIMPLE, t7 will determine whether the Poly
772
will be XORed into the entire register. If t7=1, this will happen,
773
otherwise it will not. Suppose that the top 8 bits of the poly are g7
774
g6.. g0, then after the next iteration, the top byte will be:
775

    
776
        t6 t5 t4 t3 t2 t1 t0 ??
777
+ t7 * (g7 g6 g5 g4 g3 g2 g1 g0)    [Reminder: + is XOR]
778

    
779
The NEW top bit (that will control what happens in the next iteration)
780
now has the value t6 + t7*g7. The important thing to notice here is
781
that from an informational point of view, all the information required
782
to calculate the NEW top bit was present in the top TWO bits of the
783
original top byte. Similarly, the NEXT top bit can be calculated in
784
advance SOLELY from the top THREE bits t7, t6, and t5. In fact, in
785
general, the value of the top bit in the register in k iterations can
786
be calculated from the top k bits of the register. Let us take this
787
for granted for a moment.
788

    
789
Consider for a moment that we use the top 8 bits of the register to
790
calculate the value of the top bit of the register during the next 8
791
iterations. Suppose that we drive the next 8 iterations using the
792
calculated values (which we could perhaps store in a single byte
793
register and shift out to pick off each bit). Then we note three
794
things:
795

    
796
   * The top byte of the register now doesn't matter. No matter how
797
     many times and at what offset the poly is XORed to the top 8
798
     bits, they will all be shifted out the right hand side during the
799
     next 8 iterations anyway.
800

    
801

    
802
   * The remaining bits will be shifted left one position and the
803
     rightmost byte of the register will be shifted in the next byte
804

    
805
   AND
806

    
807
   * While all this is going on, the register will be subjected to a
808
     series of XOR's in accordance with the bits of the pre-calculated
809
     control byte.
810

    
811
Now consider the effect of XORing in a constant value at various
812
offsets to a register. For example:
813

    
814
       0100010  Register
815
       ...0110  XOR this
816
       ..0110.  XOR this
817
       0110...  XOR this
818
       -------
819
       0011000
820
       -------
821

    
822
The point of this is that you can XOR constant values into a register
823
to your heart's delight, and in the end, there will exist a value
824
which when XORed in with the original register will have the same
825
effect as all the other XORs.
826

    
827
Perhaps you can see the solution now. Putting all the pieces together
828
we have an algorithm that goes like this:
829

    
830
   While (augmented message is not exhausted)
831
      Begin
832
      Examine the top byte of the register
833
      Calculate the control byte from the top byte of the register
834
      Sum all the Polys at various offsets that are to be XORed into
835
         the register in accordance with the control byte
836
      Shift the register left by one byte, reading a new message byte
837
         into the rightmost byte of the register
838
      XOR the summed polys to the register
839
      End
840

    
841
As it stands this is not much better than the SIMPLE algorithm.
842
However, it turns out that most of the calculation can be precomputed
843
and assembled into a table. As a result, the above algorithm can be
844
reduced to:
845

    
846
   While (augmented message is not exhaused)
847
      Begin
848
      Top = top_byte(Register);
849
      Register = (Register << 24) | next_augmessage_byte;
850
      Register = Register XOR precomputed_table[Top];
851
      End
852

    
853
There! If you understand this, you've grasped the main idea of
854
table-driven CRC algorithms. The above is a very efficient algorithm
855
requiring just a shift, and OR, an XOR, and a table lookup per byte.
856
Graphically, it looks like this:
857

    
858
                   3    2    1    0   Bytes
859
                +----+----+----+----+
860
         +-----<|    |    |    |    | <----- Augmented message
861
         |      +----+----+----+----+
862
         |                ^
863
         |                |
864
         |               XOR
865
         |                |
866
         |     0+----+----+----+----+       Algorithm
867
         v      +----+----+----+----+       ---------
868
         |      +----+----+----+----+       1. Shift the register left by
869
         |      +----+----+----+----+          one byte, reading in a new
870
         |      +----+----+----+----+          message byte.
871
         |      +----+----+----+----+       2. Use the top byte just rotated
872
         |      +----+----+----+----+          out of the register to index
873
         +----->+----+----+----+----+          the table of 256 32-bit values.
874
                +----+----+----+----+       3. XOR the table value into the
875
                +----+----+----+----+          register.
876
                +----+----+----+----+       4. Goto 1 iff more augmented
877
                +----+----+----+----+          message bytes.
878
             255+----+----+----+----+
879

    
880

    
881
In C, the algorithm main loop looks like this:
882

    
883
   r=0;
884
   while (len--)
885
     {
886
      byte t = (r >> 24) & 0xFF;
887
      r = (r << 8) | *p++;
888
      r^=table[t];
889
     }
890

    
891
where len is the length of the augmented message in bytes, p points to
892
the augmented message, r is the register, t is a temporary, and table
893
is the computed table. This code can be made even more unreadable as
894
follows:
895

    
896
   r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
897

    
898
This is a very clean, efficient loop, although not a very obvious one
899
to the casual observer not versed in CRC theory. We will call this the
900
TABLE algorithm.
901

    
902

    
903
10. A Slightly Mangled Table-Driven Implementation
904
--------------------------------------------------
905
Despite the terse beauty of the line
906

    
907
   r=0; while (len--) r = ((r << 8) | *p++) ^ t[(r >> 24) & 0xFF];
908

    
909
those optimizing hackers couldn't leave it alone. The trouble, you
910
see, is that this loop operates upon the AUGMENTED message and in
911
order to use this code, you have to append W/8 zero bytes to the end
912
of the message before pointing p at it. Depending on the run-time
913
environment, this may or may not be a problem; if the block of data
914
was handed to us by some other code, it could be a BIG problem. One
915
alternative is simply to append the following line after the above
916
loop, once for each zero byte:
917

    
918
      for (i=0; i<W/4; i++) r = (r << 8) ^ t[(r >> 24) & 0xFF];
919

    
920
This looks like a sane enough solution to me. However, at the further
921
expense of clarity (which, you must admit, is already a pretty scare
922
commodity in this code) we can reorganize this small loop further so
923
as to avoid the need to either augment the message with zero bytes, or
924
to explicitly process zero bytes at the end as above. To explain the
925
optimization, we return to the processing diagram given earlier.
926

    
927
                   3    2    1    0   Bytes
928
                +----+----+----+----+
929
         +-----<|    |    |    |    | <----- Augmented message
930
         |      +----+----+----+----+
931
         |                ^
932
         |                |
933
         |               XOR
934
         |                |
935
         |     0+----+----+----+----+       Algorithm
936
         v      +----+----+----+----+       ---------
937
         |      +----+----+----+----+       1. Shift the register left by
938
         |      +----+----+----+----+          one byte, reading in a new
939
         |      +----+----+----+----+          message byte.
940
         |      +----+----+----+----+       2. Use the top byte just rotated
941
         |      +----+----+----+----+          out of the register to index
942
         +----->+----+----+----+----+          the table of 256 32-bit values.
943
                +----+----+----+----+       3. XOR the table value into the
944
                +----+----+----+----+          register.
945
                +----+----+----+----+       4. Goto 1 iff more augmented
946
                +----+----+----+----+          message bytes.
947
             255+----+----+----+----+
948

    
949
Now, note the following facts:
950

    
951
TAIL: The W/4 augmented zero bytes that appear at the end of the
952
      message will be pushed into the register from the right as all
953
      the other bytes are, but their values (0) will have no effect
954
      whatsoever on the register because 1) XORing with zero does not
955
      change the target byte, and 2) the four bytes are never
956
      propagated out the left side of the register where their
957
      zeroness might have some sort of influence. Thus, the sole
958
      function of the W/4 augmented zero bytes is to drive the
959
      calculation for another W/4 byte cycles so that the end of the
960
      REAL data passes all the way through the register.
961

    
962
HEAD: If the initial value of the register is zero, the first four
963
      iterations of the loop will have the sole effect of shifting in
964
      the first four bytes of the message from the right. This is
965
      because the first 32 control bits are all zero and so nothing is
966
      XORed into the register. Even if the initial value is not zero,
967
      the first 4 byte iterations of the algorithm will have the sole
968
      effect of shifting the first 4 bytes of the message into the
969
      register and then XORing them with some constant value (that is
970
      a function of the initial value of the register).
971

    
972
These facts, combined with the XOR property
973

    
974
   (A xor B) xor C = A xor (B xor C)
975

    
976
mean that message bytes need not actually travel through the W/4 bytes
977
of the register. Instead, they can be XORed into the top byte just
978
before it is used to index the lookup table. This leads to the
979
following modified version of the algorithm.
980

    
981

    
982
         +-----<Message (non augmented)
983
         |
984
         v         3    2    1    0   Bytes
985
         |      +----+----+----+----+
986
        XOR----<|    |    |    |    |
987
         |      +----+----+----+----+
988
         |                ^
989
         |                |
990
         |               XOR
991
         |                |
992
         |     0+----+----+----+----+       Algorithm
993
         v      +----+----+----+----+       ---------
994
         |      +----+----+----+----+       1. Shift the register left by
995
         |      +----+----+----+----+          one byte, reading in a new
996
         |      +----+----+----+----+          message byte.
997
         |      +----+----+----+----+       2. XOR the top byte just rotated
998
         |      +----+----+----+----+          out of the register with the
999
         +----->+----+----+----+----+          next message byte to yield an
1000
                +----+----+----+----+          index into the table ([0,255]).
1001
                +----+----+----+----+       3. XOR the table value into the
1002
                +----+----+----+----+          register.
1003
                +----+----+----+----+       4. Goto 1 iff more augmented
1004
             255+----+----+----+----+          message bytes.
1005

    
1006

    
1007
Note: The initial register value for this algorithm must be the
1008
initial value of the register for the previous algorithm fed through
1009
the table four times. Note: The table is such that if the previous
1010
algorithm used 0, the new algorithm will too.
1011

    
1012
This is an IDENTICAL algorithm and will yield IDENTICAL results. The C
1013
code looks something like this:
1014

    
1015
   r=0; while (len--) r = (r<<8) ^ t[(r >> 24) ^ *p++];
1016

    
1017
and THIS is the code that you are likely to find inside current
1018
table-driven CRC implementations. Some FF masks might have to be ANDed
1019
in here and there for portability's sake, but basically, the above
1020
loop is IT. We will call this the DIRECT TABLE ALGORITHM.
1021

    
1022
During the process of trying to understand all this stuff, I managed
1023
to derive the SIMPLE algorithm and the table-driven version derived
1024
from that. However, when I compared my code with the code found in
1025
real-implementations, I was totally bamboozled as to why the bytes
1026
were being XORed in at the wrong end of the register! It took quite a
1027
while before I figured out that theirs and my algorithms were actually
1028
the same. Part of why I am writing this document is that, while the
1029
link between division and my earlier table-driven code is vaguely
1030
apparent, any such link is fairly well erased when you start pumping
1031
bytes in at the "wrong end" of the register. It looks all wrong!
1032

    
1033
If you've got this far, you not only understand the theory, the
1034
practice, the optimized practice, but you also understand the real
1035
code you are likely to run into. Could get any more complicated? Yes
1036
it can.
1037

    
1038

    
1039
11. "Reflected" Table-Driven Implementations
1040
--------------------------------------------
1041
Despite the fact that the above code is probably optimized about as
1042
much as it could be, this did not stop some enterprising individuals
1043
from making things even more complicated. To understand how this
1044
happened, we have to enter the world of hardware.
1045

    
1046
DEFINITION: A value/register is reflected if it's bits are swapped
1047
around its centre. For example: 0101 is the 4-bit reflection of 1010.
1048
0011 is the reflection of 1100.
1049
0111-0101-1010-1111-0010-0101-1011-1100 is the reflection of
1050
0011-1101-1010-0100-1111-0101-1010-1110.
1051

    
1052
Turns out that UARTs (those handy little chips that perform serial IO)
1053
are in the habit of transmitting each byte with the least significant
1054
bit (bit 0) first and the most significant bit (bit 7) last (i.e.
1055
reflected). An effect of this convention is that hardware engineers
1056
constructing hardware CRC calculators that operate at the bit level
1057
took to calculating CRCs of bytes streams with each of the bytes
1058
reflected within itself. The bytes are processed in the same order,
1059
but the bits in each byte are swapped; bit 0 is now bit 7, bit 1 is
1060
now bit 6, and so on. Now this wouldn't matter much if this convention
1061
was restricted to hardware land. However it seems that at some stage
1062
some of these CRC values were presented at the software level and
1063
someone had to write some code that would interoperate with the
1064
hardware CRC calculation.
1065

    
1066
In this situation, a normal sane software engineer would simply
1067
reflect each byte before processing it. However, it would seem that
1068
normal sane software engineers were thin on the ground when this early
1069
ground was being broken, because instead of reflecting the bytes,
1070
whoever was responsible held down the byte and reflected the world,
1071
leading to the following "reflected" algorithm which is identical to
1072
the previous one except that everything is reflected except the input
1073
bytes.
1074

    
1075

    
1076
             Message (non augmented) >-----+
1077
                                           |
1078
           Bytes   0    1    2    3        v
1079
                +----+----+----+----+      |
1080
                |    |    |    |    |>----XOR
1081
                +----+----+----+----+      |
1082
                          ^                |
1083
                          |                |
1084
                         XOR               |
1085
                          |                |
1086
                +----+----+----+----+0     |
1087
                +----+----+----+----+      v
1088
                +----+----+----+----+      |
1089
                +----+----+----+----+      |
1090
                +----+----+----+----+      |
1091
                +----+----+----+----+      |
1092
                +----+----+----+----+      |
1093
                +----+----+----+----+<-----+
1094
                +----+----+----+----+
1095
                +----+----+----+----+
1096
                +----+----+----+----+
1097
                +----+----+----+----+
1098
                +----+----+----+----+255
1099

    
1100
Notes:
1101

    
1102
   * The table is identical to the one in the previous algorithm
1103
   except that each entry has been reflected.
1104

    
1105
   * The initial value of the register is the same as in the previous
1106
   algorithm except that it has been reflected.
1107

    
1108
   * The bytes of the message are processed in the same order as
1109
   before (i.e. the message itself is not reflected).
1110

    
1111
   * The message bytes themselves don't need to be explicitly
1112
   reflected, because everything else has been!
1113

    
1114
At the end of execution, the register contains the reflection of the
1115
final CRC value (remainder). Actually, I'm being rather hard on
1116
whoever cooked this up because it seems that hardware implementations
1117
of the CRC algorithm used the reflected checksum value and so
1118
producing a reflected CRC was just right. In fact reflecting the world
1119
was probably a good engineering solution - if a confusing one.
1120

    
1121
We will call this the REFLECTED algorithm.
1122

    
1123
Whether or not it made sense at the time, the effect of having
1124
reflected algorithms kicking around the world's FTP sites is that
1125
about half the CRC implementations one runs into are reflected and the
1126
other half not. It's really terribly confusing. In particular, it
1127
would seem to me that the casual reader who runs into a reflected,
1128
table-driven implementation with the bytes "fed in the wrong end"
1129
would have Buckley's chance of ever connecting the code to the concept
1130
of binary mod 2 division.
1131

    
1132
It couldn't get any more confusing could it? Yes it could.
1133

    
1134

    
1135
12. "Reversed" Polys
1136
--------------------
1137
As if reflected implementations weren't enough, there is another
1138
concept kicking around which makes the situation bizaarly confusing.
1139
The concept is reversed Polys.
1140

    
1141
It turns out that the reflection of good polys tend to be good polys
1142
too! That is, if G=11101 is a good poly value, then 10111 will be as
1143
well. As a consequence, it seems that every time an organization (such
1144
as CCITT) standardizes on a particularly good poly ("polynomial"),
1145
those in the real world can't leave the poly's reflection alone
1146
either. They just HAVE to use it. As a result, the set of "standard"
1147
poly's has a corresponding set of reflections, which are also in use.
1148
To avoid confusion, we will call these the "reversed" polys.
1149

    
1150
   X25   standard: 1-0001-0000-0010-0001
1151
   X25   reversed: 1-0000-1000-0001-0001
1152

    
1153
   CRC16 standard: 1-1000-0000-0000-0101
1154
   CRC16 reversed: 1-0100-0000-0000-0011
1155

    
1156
Note that here it is the entire poly that is being reflected/reversed,
1157
not just the bottom W bits. This is an important distinction. In the
1158
reflected algorithm described in the previous section, the poly used
1159
in the reflected algorithm was actually identical to that used in the
1160
non-reflected algorithm; all that had happened is that the bytes had
1161
effectively been reflected. As such, all the 16-bit/32-bit numbers in
1162
the algorithm had to be reflected. In contrast, the ENTIRE poly
1163
includes the implicit one bit at the top, and so reversing a poly is
1164
not the same as reflecting its bottom 16 or 32 bits.
1165

    
1166
The upshot of all this is that a reflected algorithm is not equivalent
1167
to the original algorithm with the poly reflected. Actually, this is
1168
probably less confusing than if they were duals.
1169

    
1170
If all this seems a bit unclear, don't worry, because we're going to
1171
sort it all out "real soon now". Just one more section to go before
1172
that.
1173

    
1174

    
1175
13. Initial and Final Values
1176
----------------------------
1177
In addition to the complexity already seen, CRC algorithms differ from
1178
each other in two other regards:
1179

    
1180
   * The initial value of the register.
1181

    
1182
   * The value to be XORed with the final register value.
1183

    
1184
For example, the "CRC32" algorithm initializes its register to
1185
FFFFFFFF and XORs the final register value with FFFFFFFF.
1186

    
1187
Most CRC algorithms initialize their register to zero. However, some
1188
initialize it to a non-zero value. In theory (i.e. with no assumptions
1189
about the message), the initial value has no affect on the strength of
1190
the CRC algorithm, the initial value merely providing a fixed starting
1191
point from which the register value can progress. However, in
1192
practice, some messages are more likely than others, and it is wise to
1193
initialize the CRC algorithm register to a value that does not have
1194
"blind spots" that are likely to occur in practice. By "blind spot" is
1195
meant a sequence of message bytes that do not result in the register
1196
changing its value. In particular, any CRC algorithm that initializes
1197
its register to zero will have a blind spot of zero when it starts up
1198
and will be unable to "count" a leading run of zero bytes. As a
1199
leading run of zero bytes is quite common in real messages, it is wise
1200
to initialize the algorithm register to a non-zero value.
1201

    
1202

    
1203
14. Defining Algorithms Absolutely
1204
----------------------------------
1205
At this point we have covered all the different aspects of
1206
table-driven CRC algorithms. As there are so many variations on these
1207
algorithms, it is worth trying to establish a nomenclature for them.
1208
This section attempts to do that.
1209

    
1210
We have seen that CRC algorithms vary in:
1211

    
1212
   * Width of the poly (polynomial).
1213
   * Value of the poly.
1214
   * Initial value for the register.
1215
   * Whether the bits of each byte are reflected before being processed.
1216
   * Whether the algorithm feeds input bytes through the register or
1217
     xors them with a byte from one end and then straight into the table.
1218
   * Whether the final register value should be reversed (as in reflected
1219
     versions).
1220
   * Value to XOR with the final register value.
1221

    
1222
In order to be able to talk about particular CRC algorithms, we need
1223
to able to define them more precisely than this. For this reason, the
1224
next section attempts to provide a well-defined parameterized model
1225
for CRC algorithms. To refer to a particular algorithm, we need then
1226
simply specify the algorithm in terms of parameters to the model.
1227

    
1228

    
1229
15. A Parameterized Model For CRC Algorithms
1230
--------------------------------------------
1231
In this section we define a precise parameterized model CRC algorithm
1232
which, for want of a better name, we will call the "Rocksoft^tm Model
1233
CRC Algorithm" (and why not? Rocksoft^tm could do with some free
1234
advertising :-).
1235

    
1236
The most important aspect of the model algorithm is that it focusses
1237
exclusively on functionality, ignoring all implementation details. The
1238
aim of the exercise is to construct a way of referring precisely to
1239
particular CRC algorithms, regardless of how confusingly they are
1240
implemented. To this end, the model must be as simple and precise as
1241
possible, with as little confusion as possible.
1242

    
1243
The Rocksoft^tm Model CRC Algorithm is based essentially on the DIRECT
1244
TABLE ALGORITHM specified earlier. However, the algorithm has to be
1245
further parameterized to enable it to behave in the same way as some
1246
of the messier algorithms out in the real world.
1247

    
1248
To enable the algorithm to behave like reflected algorithms, we
1249
provide a boolean option to reflect the input bytes, and a boolean
1250
option to specify whether to reflect the output checksum value. By
1251
framing reflection as an input/output transformation, we avoid the
1252
confusion of having to mentally map the parameters of reflected and
1253
non-reflected algorithms.
1254

    
1255
An extra parameter allows the algorithm's register to be initialized
1256
to a particular value. A further parameter is XORed with the final
1257
value before it is returned.
1258

    
1259
By putting all these pieces together we end up with the parameters of
1260
the algorithm:
1261

    
1262
   NAME: This is a name given to the algorithm. A string value.
1263

    
1264
   WIDTH: This is the width of the algorithm expressed in bits. This
1265
   is one less than the width of the Poly.
1266

    
1267
   POLY: This parameter is the poly. This is a binary value that
1268
   should be specified as a hexadecimal number. The top bit of the
1269
   poly should be omitted. For example, if the poly is 10110, you
1270
   should specify 06. An important aspect of this parameter is that it
1271
   represents the unreflected poly; the bottom bit of this parameter
1272
   is always the LSB of the divisor during the division regardless of
1273
   whether the algorithm being modelled is reflected.
1274

    
1275
   INIT: This parameter specifies the initial value of the register
1276
   when the algorithm starts. This is the value that is to be assigned
1277
   to the register in the direct table algorithm. In the table
1278
   algorithm, we may think of the register always commencing with the
1279
   value zero, and this value being XORed into the register after the
1280
   N'th bit iteration. This parameter should be specified as a
1281
   hexadecimal number.
1282

    
1283
   REFIN: This is a boolean parameter. If it is FALSE, input bytes are
1284
   processed with bit 7 being treated as the most significant bit
1285
   (MSB) and bit 0 being treated as the least significant bit. If this
1286
   parameter is FALSE, each byte is reflected before being processed.
1287

    
1288
   REFOUT: This is a boolean parameter. If it is set to FALSE, the
1289
   final value in the register is fed into the XOROUT stage directly,
1290
   otherwise, if this parameter is TRUE, the final register value is
1291
   reflected first.
1292

    
1293
   XOROUT: This is an W-bit value that should be specified as a
1294
   hexadecimal number. It is XORed to the final register value (after
1295
   the REFOUT) stage before the value is returned as the official
1296
   checksum.
1297

    
1298
   CHECK: This field is not strictly part of the definition, and, in
1299
   the event of an inconsistency between this field and the other
1300
   field, the other fields take precedence. This field is a check
1301
   value that can be used as a weak validator of implementations of
1302
   the algorithm. The field contains the checksum obtained when the
1303
   ASCII string "123456789" is fed through the specified algorithm
1304
   (i.e. 313233... (hexadecimal)).
1305

    
1306
With these parameters defined, the model can now be used to specify a
1307
particular CRC algorithm exactly. Here is an example specification for
1308
a popular form of the CRC-16 algorithm.
1309

    
1310
   Name   : "CRC-16"
1311
   Width  : 16
1312
   Poly   : 8005
1313
   Init   : 0000
1314
   RefIn  : True
1315
   RefOut : True
1316
   XorOut : 0000
1317
   Check  : BB3D
1318

    
1319

    
1320
16. A Catalog of Parameter Sets for Standards
1321
---------------------------------------------
1322
At this point, I would like to give a list of the specifications for
1323
commonly used CRC algorithms. However, most of the algorithms that I
1324
have come into contact with so far are specified in such a vague way
1325
that this has not been possible. What I can provide is a list of polys
1326
for various CRC standards I have heard of:
1327

    
1328
   X25   standard : 1021       [CRC-CCITT, ADCCP, SDLC/HDLC]
1329
   X25   reversed : 0811
1330

    
1331
   CRC16 standard : 8005
1332
   CRC16 reversed : 4003       [LHA]
1333

    
1334
   CRC32          : 04C11DB7   [PKZIP, AUTODIN II, Ethernet, FDDI]
1335

    
1336
I would be interested in hearing from anyone out there who can tie
1337
down the complete set of model parameters for any of these standards.
1338

    
1339
However, a program that was kicking around seemed to imply the
1340
following specifications. Can anyone confirm or deny them (or provide
1341
the check values (which I couldn't be bothered coding up and
1342
calculating)).
1343

    
1344
   Name   : "CRC-16/CITT"
1345
   Width  : 16
1346
   Poly   : 1021
1347
   Init   : FFFF
1348
   RefIn  : False
1349
   RefOut : False
1350
   XorOut : 0000
1351
   Check  : ?
1352

    
1353

    
1354
   Name   : "XMODEM"
1355
   Width  : 16
1356
   Poly   : 8408
1357
   Init   : 0000
1358
   RefIn  : True
1359
   RefOut : True
1360
   XorOut : 0000
1361
   Check  : ?
1362

    
1363

    
1364
   Name   : "ARC"
1365
   Width  : 16
1366
   Poly   : 8005
1367
   Init   : 0000
1368
   RefIn  : True
1369
   RefOut : True
1370
   XorOut : 0000
1371
   Check  : ?
1372

    
1373
Here is the specification for the CRC-32 algorithm which is reportedly
1374
used in PKZip, AUTODIN II, Ethernet, and FDDI.
1375

    
1376
   Name   : "CRC-32"
1377
   Width  : 32
1378
   Poly   : 04C11DB7
1379
   Init   : FFFFFFFF
1380
   RefIn  : True
1381
   RefOut : True
1382
   XorOut : FFFFFFFF
1383
   Check  : CBF43926
1384

    
1385

    
1386
17. An Implementation of the Model Algorithm
1387
--------------------------------------------
1388
Here is an implementation of the model algorithm in the C programming
1389
language. The implementation consists of a header file (.h) and an
1390
implementation file (.c). If you're reading this document in a
1391
sequential scroller, you can skip this code by searching for the
1392
string "Roll Your Own".
1393

    
1394
To ensure that the following code is working, configure it for the
1395
CRC-16 and CRC-32 algorithms given above and ensure that they produce
1396
the specified "check" checksum when fed the test string "123456789"
1397
(see earlier).
1398

    
1399
/******************************************************************************/
1400
/*                             Start of crcmodel.h                            */
1401
/******************************************************************************/
1402
/*                                                                            */
1403
/* Author : Ross Williams (ross@guest.adelaide.edu.au.).                      */
1404
/* Date   : 3 June 1993.                                                      */
1405
/* Status : Public domain.                                                    */
1406
/*                                                                            */
1407
/* Description : This is the header (.h) file for the reference               */
1408
/* implementation of the Rocksoft^tm Model CRC Algorithm. For more            */
1409
/* information on the Rocksoft^tm Model CRC Algorithm, see the document       */
1410
/* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross        */
1411
/* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in   */
1412
/* "ftp.adelaide.edu.au/pub/rocksoft".                                        */
1413
/*                                                                            */
1414
/* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.    */
1415
/*                                                                            */
1416
/******************************************************************************/
1417
/*                                                                            */
1418
/* How to Use This Package                                                    */
1419
/* -----------------------                                                    */
1420
/* Step 1: Declare a variable of type cm_t. Declare another variable          */
1421
/*         (p_cm say) of type p_cm_t and initialize it to point to the first  */
1422
/*         variable (e.g. p_cm_t p_cm = &cm_t).                               */
1423
/*                                                                            */
1424
/* Step 2: Assign values to the parameter fields of the structure.            */
1425
/*         If you don't know what to assign, see the document cited earlier.  */
1426
/*         For example:                                                       */
1427
/*            p_cm->cm_width = 16;                                            */
1428
/*            p_cm->cm_poly  = 0x8005L;                                       */
1429
/*            p_cm->cm_init  = 0L;                                            */
1430
/*            p_cm->cm_refin = TRUE;                                          */
1431
/*            p_cm->cm_refot = TRUE;                                          */
1432
/*            p_cm->cm_xorot = 0L;                                            */
1433
/*         Note: Poly is specified without its top bit (18005 becomes 8005).  */
1434
/*         Note: Width is one bit less than the raw poly width.               */
1435
/*                                                                            */
1436
/* Step 3: Initialize the instance with a call cm_ini(p_cm);                  */
1437
/*                                                                            */
1438
/* Step 4: Process zero or more message bytes by placing zero or more         */
1439
/*         successive calls to cm_nxt. Example: cm_nxt(p_cm,ch);              */
1440
/*                                                                            */
1441
/* Step 5: Extract the CRC value at any time by calling crc = cm_crc(p_cm);   */
1442
/*         If the CRC is a 16-bit value, it will be in the bottom 16 bits.    */
1443
/*                                                                            */
1444
/******************************************************************************/
1445
/*                                                                            */
1446
/* Design Notes                                                               */
1447
/* ------------                                                               */
1448
/* PORTABILITY: This package has been coded very conservatively so that       */
1449
/* it will run on as many machines as possible. For example, all external     */
1450
/* identifiers have been restricted to 6 characters and all internal ones to  */
1451
/* 8 characters. The prefix cm (for Crc Model) is used as an attempt to avoid */
1452
/* namespace collisions. This package is endian independent.                  */
1453
/*                                                                            */
1454
/* EFFICIENCY: This package (and its interface) is not designed for           */
1455
/* speed. The purpose of this package is to act as a well-defined reference   */
1456
/* model for the specification of CRC algorithms. If you want speed, cook up  */
1457
/* a specific table-driven implementation as described in the document cited  */
1458
/* above. This package is designed for validation only; if you have found or  */
1459
/* implemented a CRC algorithm and wish to describe it as a set of parameters */
1460
/* to the Rocksoft^tm Model CRC Algorithm, your CRC algorithm implementation  */
1461
/* should behave identically to this package under those parameters.          */
1462
/*                                                                            */
1463
/******************************************************************************/
1464

    
1465
/* The following #ifndef encloses this entire */
1466
/* header file, rendering it indempotent.     */
1467
#ifndef CM_DONE
1468
#define CM_DONE
1469

    
1470
/******************************************************************************/
1471

    
1472
/* The following definitions are extracted from my style header file which    */
1473
/* would be cumbersome to distribute with this package. The DONE_STYLE is the */
1474
/* idempotence symbol used in my style header file.                           */
1475

    
1476
#ifndef DONE_STYLE
1477

    
1478
typedef unsigned long   ulong;
1479
typedef unsigned        bool;
1480
typedef unsigned char * p_ubyte_;
1481

    
1482
#ifndef TRUE
1483
#define FALSE 0
1484
#define TRUE  1
1485
#endif
1486

    
1487
/* Change to the second definition if you don't have prototypes. */
1488
#define P_(A) A
1489
/* #define P_(A) () */
1490

    
1491
/* Uncomment this definition if you don't have void. */
1492
/* typedef int void; */
1493

    
1494
#endif
1495

    
1496
/******************************************************************************/
1497

    
1498
/* CRC Model Abstract Type */
1499
/* ----------------------- */
1500
/* The following type stores the context of an executing instance of the  */
1501
/* model algorithm. Most of the fields are model parameters which must be */
1502
/* set before the first initializing call to cm_ini.                      */
1503
typedef struct
1504
  {
1505
   int   cm_width;   /* Parameter: Width in bits [8,32].       */
1506
   ulong cm_poly;    /* Parameter: The algorithm's polynomial. */
1507
   ulong cm_init;    /* Parameter: Initial register value.     */
1508
   bool  cm_refin;   /* Parameter: Reflect input bytes?        */
1509
   bool  cm_refot;   /* Parameter: Reflect output CRC?         */
1510
   ulong cm_xorot;   /* Parameter: XOR this to output CRC.     */
1511

    
1512
   ulong cm_reg;     /* Context: Context during execution.     */
1513
  } cm_t;
1514
typedef cm_t *p_cm_t;
1515

    
1516
/******************************************************************************/
1517

    
1518
/* Functions That Implement The Model */
1519
/* ---------------------------------- */
1520
/* The following functions animate the cm_t abstraction. */
1521

    
1522
void cm_ini P_((p_cm_t p_cm));
1523
/* Initializes the argument CRC model instance.          */
1524
/* All parameter fields must be set before calling this. */
1525

    
1526
void cm_nxt P_((p_cm_t p_cm,int ch));
1527
/* Processes a single message byte [0,255]. */
1528

    
1529
void cm_blk P_((p_cm_t p_cm,p_ubyte_ blk_adr,ulong blk_len));
1530
/* Processes a block of message bytes. */
1531

    
1532
ulong cm_crc P_((p_cm_t p_cm));
1533
/* Returns the CRC value for the message bytes processed so far. */
1534

    
1535
/******************************************************************************/
1536

    
1537
/* Functions For Table Calculation */
1538
/* ------------------------------- */
1539
/* The following function can be used to calculate a CRC lookup table.        */
1540
/* It can also be used at run-time to create or check static tables.          */
1541

    
1542
ulong cm_tab P_((p_cm_t p_cm,int index));
1543
/* Returns the i'th entry for the lookup table for the specified algorithm.   */
1544
/* The function examines the fields cm_width, cm_poly, cm_refin, and the      */
1545
/* argument table index in the range [0,255] and returns the table entry in   */
1546
/* the bottom cm_width bytes of the return value.                             */
1547

    
1548
/******************************************************************************/
1549

    
1550
/* End of the header file idempotence #ifndef */
1551
#endif
1552

    
1553
/******************************************************************************/
1554
/*                             End of crcmodel.h                              */
1555
/******************************************************************************/
1556

    
1557

    
1558
/******************************************************************************/
1559
/*                             Start of crcmodel.c                            */
1560
/******************************************************************************/
1561
/*                                                                            */
1562
/* Author : Ross Williams (ross@guest.adelaide.edu.au.).                      */
1563
/* Date   : 3 June 1993.                                                      */
1564
/* Status : Public domain.                                                    */
1565
/*                                                                            */
1566
/* Description : This is the implementation (.c) file for the reference       */
1567
/* implementation of the Rocksoft^tm Model CRC Algorithm. For more            */
1568
/* information on the Rocksoft^tm Model CRC Algorithm, see the document       */
1569
/* titled "A Painless Guide to CRC Error Detection Algorithms" by Ross        */
1570
/* Williams (ross@guest.adelaide.edu.au.). This document is likely to be in   */
1571
/* "ftp.adelaide.edu.au/pub/rocksoft".                                        */
1572
/*                                                                            */
1573
/* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.    */
1574
/*                                                                            */
1575
/******************************************************************************/
1576
/*                                                                            */
1577
/* Implementation Notes                                                       */
1578
/* --------------------                                                       */
1579
/* To avoid inconsistencies, the specification of each function is not echoed */
1580
/* here. See the header file for a description of these functions.            */
1581
/* This package is light on checking because I want to keep it short and      */
1582
/* simple and portable (i.e. it would be too messy to distribute my entire    */
1583
/* C culture (e.g. assertions package) with this package.                     */
1584
/*                                                                            */
1585
/******************************************************************************/
1586

    
1587
#include "crcmodel.h"
1588

    
1589
/******************************************************************************/
1590

    
1591
/* The following definitions make the code more readable. */
1592

    
1593
#define BITMASK(X) (1L << (X))
1594
#define MASK32 0xFFFFFFFFL
1595
#define LOCAL static
1596

    
1597
/******************************************************************************/
1598

    
1599
LOCAL ulong reflect P_((ulong v,int b));
1600
LOCAL ulong reflect (v,b)
1601
/* Returns the value v with the bottom b [0,32] bits reflected. */
1602
/* Example: reflect(0x3e23L,3) == 0x3e26                        */
1603
ulong v;
1604
int   b;
1605
{
1606
 int   i;
1607
 ulong t = v;
1608
 for (i=0; i<b; i++)
1609
   {
1610
    if (t & 1L)
1611
       v|=  BITMASK((b-1)-i);
1612
    else
1613
       v&= ~BITMASK((b-1)-i);
1614
    t>>=1;
1615
   }
1616
 return v;
1617
}
1618

    
1619
/******************************************************************************/
1620

    
1621
LOCAL ulong widmask P_((p_cm_t));
1622
LOCAL ulong widmask (p_cm)
1623
/* Returns a longword whose value is (2^p_cm->cm_width)-1.     */
1624
/* The trick is to do this portably (e.g. without doing <<32). */
1625
p_cm_t p_cm;
1626
{
1627
 return (((1L<<(p_cm->cm_width-1))-1L)<<1)|1L;
1628
}
1629

    
1630
/******************************************************************************/
1631

    
1632
void cm_ini (p_cm)
1633
p_cm_t p_cm;
1634
{
1635
 p_cm->cm_reg = p_cm->cm_init;
1636
}
1637

    
1638
/******************************************************************************/
1639

    
1640
void cm_nxt (p_cm,ch)
1641
p_cm_t p_cm;
1642
int    ch;
1643
{
1644
 int   i;
1645
 ulong uch  = (ulong) ch;
1646
 ulong topbit = BITMASK(p_cm->cm_width-1);
1647

    
1648
 if (p_cm->cm_refin) uch = reflect(uch,8);
1649
 p_cm->cm_reg ^= (uch << (p_cm->cm_width-8));
1650
 for (i=0; i<8; i++)
1651
   {
1652
    if (p_cm->cm_reg & topbit)
1653
       p_cm->cm_reg = (p_cm->cm_reg << 1) ^ p_cm->cm_poly;
1654
    else
1655
       p_cm->cm_reg <<= 1;
1656
    p_cm->cm_reg &= widmask(p_cm);
1657
   }
1658
}
1659

    
1660
/******************************************************************************/
1661

    
1662
void cm_blk (p_cm,blk_adr,blk_len)
1663
p_cm_t   p_cm;
1664
p_ubyte_ blk_adr;
1665
ulong    blk_len;
1666
{
1667
 while (blk_len--) cm_nxt(p_cm,*blk_adr++);
1668
}
1669

    
1670
/******************************************************************************/
1671

    
1672
ulong cm_crc (p_cm)
1673
p_cm_t p_cm;
1674
{
1675
 if (p_cm->cm_refot)
1676
    return p_cm->cm_xorot ^ reflect(p_cm->cm_reg,p_cm->cm_width);
1677
 else
1678
    return p_cm->cm_xorot ^ p_cm->cm_reg;
1679
}
1680

    
1681
/******************************************************************************/
1682

    
1683
ulong cm_tab (p_cm,index)
1684
p_cm_t p_cm;
1685
int    index;
1686
{
1687
 int   i;
1688
 ulong r;
1689
 ulong topbit = BITMASK(p_cm->cm_width-1);
1690
 ulong inbyte = (ulong) index;
1691

    
1692
 if (p_cm->cm_refin) inbyte = reflect(inbyte,8);
1693
 r = inbyte << (p_cm->cm_width-8);
1694
 for (i=0; i<8; i++)
1695
    if (r & topbit)
1696
       r = (r << 1) ^ p_cm->cm_poly;
1697
    else
1698
       r<<=1;
1699
 if (p_cm->cm_refin) r = reflect(r,p_cm->cm_width);
1700
 return r & widmask(p_cm);
1701
}
1702

    
1703
/******************************************************************************/
1704
/*                             End of crcmodel.c                              */
1705
/******************************************************************************/
1706

    
1707

    
1708
18. Roll Your Own Table-Driven Implementation
1709
---------------------------------------------
1710
Despite all the fuss I've made about understanding and defining CRC
1711
algorithms, the mechanics of their high-speed implementation remains
1712
trivial. There are really only two forms: normal and reflected. Normal
1713
shifts to the left and covers the case of algorithms with Refin=FALSE
1714
and Refot=FALSE. Reflected shifts to the right and covers algorithms
1715
with both those parameters true. (If you want one parameter true and
1716
the other false, you'll have to figure it out for yourself!) The
1717
polynomial is embedded in the lookup table (to be discussed). The
1718
other parameters, Init and XorOt can be coded as macros. Here is the
1719
32-bit normal form (the 16-bit form is similar).
1720

    
1721
   unsigned long crc_normal ();
1722
   unsigned long crc_normal (blk_adr,blk_len)
1723
   unsigned char *blk_adr;
1724
   unsigned long  blk_len;
1725
   {
1726
    unsigned long crc = INIT;
1727
    while (blk_len--)
1728
       crc = crctable[((crc>>24) ^ *blk_adr++) & 0xFFL] ^ (crc << 8);
1729
    return crc ^ XOROT;
1730
   }
1731

    
1732
Here is the reflected form:
1733

    
1734
   unsigned long crc_reflected ();
1735
   unsigned long crc_reflected (blk_adr,blk_len)
1736
   unsigned char *blk_adr;
1737
   unsigned long  blk_len;
1738
   {
1739
    unsigned long crc = INIT_REFLECTED;
1740
    while (blk_len--)
1741
       crc = crctable[(crc ^ *blk_adr++) & 0xFFL] ^ (crc >> 8));
1742
    return crc ^ XOROT;
1743
   }
1744

    
1745
Note: I have carefully checked the above two code fragments, but I
1746
haven't actually compiled or tested them. This shouldn't matter to
1747
you, as, no matter WHAT you code, you will always be able to tell if
1748
you have got it right by running whatever you have created against the
1749
reference model given earlier. The code fragments above are really
1750
just a rough guide. The reference model is the definitive guide.
1751

    
1752
Note: If you don't care much about speed, just use the reference model
1753
code!
1754

    
1755

    
1756
19. Generating A Lookup Table
1757
-----------------------------
1758
The only component missing from the normal and reversed code fragments
1759
in the previous section is the lookup table. The lookup table can be
1760
computed at run time using the cm_tab function of the model package
1761
given earlier, or can be pre-computed and inserted into the C program.
1762
In either case, it should be noted that the lookup table depends only
1763
on the POLY and RefIn (and RefOt) parameters. Basically, the
1764
polynomial determines the table, but you can generate a reflected
1765
table too if you want to use the reflected form above.
1766

    
1767
The following program generates any desired 16-bit or 32-bit lookup
1768
table. Skip to the word "Summary" if you want to skip over this code.
1769

    
1770

    
1771

    
1772
/******************************************************************************/
1773
/*                             Start of crctable.c                            */
1774
/******************************************************************************/
1775
/*                                                                            */
1776
/* Author  : Ross Williams (ross@guest.adelaide.edu.au.).                     */
1777
/* Date    : 3 June 1993.                                                     */
1778
/* Version : 1.0.                                                             */
1779
/* Status  : Public domain.                                                   */
1780
/*                                                                            */
1781
/* Description : This program writes a CRC lookup table (suitable for         */
1782
/* inclusion in a C program) to a designated output file. The program can be  */
1783
/* statically configured to produce any table covered by the Rocksoft^tm      */
1784
/* Model CRC Algorithm. For more information on the Rocksoft^tm Model CRC     */
1785
/* Algorithm, see the document titled "A Painless Guide to CRC Error          */
1786
/* Detection Algorithms" by Ross Williams (ross@guest.adelaide.edu.au.). This */
1787
/* document is likely to be in "ftp.adelaide.edu.au/pub/rocksoft".            */
1788
/*                                                                            */
1789
/* Note: Rocksoft is a trademark of Rocksoft Pty Ltd, Adelaide, Australia.    */
1790
/*                                                                            */
1791
/******************************************************************************/
1792

    
1793
#include <stdio.h>
1794
#include <stdlib.h>
1795
#include "crcmodel.h"
1796

    
1797
/******************************************************************************/
1798

    
1799
/* TABLE PARAMETERS                                                           */
1800
/* ================                                                           */
1801
/* The following parameters entirely determine the table to be generated. You */
1802
/* should need to modify only the definitions in this section before running  */
1803
/* this program.                                                              */
1804
/*                                                                            */
1805
/*    TB_FILE  is the name of the output file.                                */
1806
/*    TB_WIDTH is the table width in bytes (either 2 or 4).                   */
1807
/*    TB_POLY  is the "polynomial", which must be TB_WIDTH bytes wide.        */
1808
/*    TB_REVER indicates whether the table is to be reversed (reflected).     */
1809
/*                                                                            */
1810
/* Example:                                                                   */
1811
/*                                                                            */
1812
/*    #define TB_FILE   "crctable.out"                                        */
1813
/*    #define TB_WIDTH  2                                                     */
1814
/*    #define TB_POLY   0x8005L                                               */
1815
/*    #define TB_REVER  TRUE                                                  */
1816

    
1817
#define TB_FILE   "crctable.out"
1818
#define TB_WIDTH  4
1819
#define TB_POLY   0x04C11DB7L
1820
#define TB_REVER  TRUE
1821

    
1822
/******************************************************************************/
1823

    
1824
/* Miscellaneous definitions. */
1825

    
1826
#define LOCAL static
1827
FILE *outfile;
1828
#define WR(X) fprintf(outfile,(X))
1829
#define WP(X,Y) fprintf(outfile,(X),(Y))
1830

    
1831
/******************************************************************************/
1832

    
1833
LOCAL void chk_err P_((char *));
1834
LOCAL void chk_err (mess)
1835
/* If mess is non-empty, write it out and abort. Otherwise, check the error   */
1836
/* status of outfile and abort if an error has occurred.                      */
1837
char *mess;
1838
{
1839
 if (mess[0] != 0   ) {printf("%s\n",mess); exit(EXIT_FAILURE);}
1840
 if (ferror(outfile)) {perror("chk_err");   exit(EXIT_FAILURE);}
1841
}
1842

    
1843
/******************************************************************************/
1844

    
1845
LOCAL void chkparam P_((void));
1846
LOCAL void chkparam ()
1847
{
1848
 if ((TB_WIDTH != 2) && (TB_WIDTH != 4))
1849
    chk_err("chkparam: Width parameter is illegal.");
1850
 if ((TB_WIDTH == 2) && (TB_POLY & 0xFFFF0000L))
1851
    chk_err("chkparam: Poly parameter is too wide.");
1852
 if ((TB_REVER != FALSE) && (TB_REVER != TRUE))
1853
    chk_err("chkparam: Reverse parameter is not boolean.");
1854
}
1855

    
1856
/******************************************************************************/
1857

    
1858
LOCAL void gentable P_((void));
1859
LOCAL void gentable ()
1860
{
1861
 WR("/*****************************************************************/\n");
1862
 WR("/*                                                               */\n");
1863
 WR("/* CRC LOOKUP TABLE                                              */\n");
1864
 WR("/* ================                                              */\n");
1865
 WR("/* The following CRC lookup table was generated automagically    */\n");
1866
 WR("/* by the Rocksoft^tm Model CRC Algorithm Table Generation       */\n");
1867
 WR("/* Program V1.0 using the following model parameters:            */\n");
1868
 WR("/*                                                               */\n");
1869
 WP("/*    Width   : %1lu bytes.                                         */\n",
1870
    (ulong) TB_WIDTH);
1871
 if (TB_WIDTH == 2)
1872
 WP("/*    Poly    : 0x%04lX                                           */\n",
1873
    (ulong) TB_POLY);
1874
 else
1875
 WP("/*    Poly    : 0x%08lXL                                      */\n",
1876
    (ulong) TB_POLY);
1877
 if (TB_REVER)
1878
 WR("/*    Reverse : TRUE.                                            */\n");
1879
 else
1880
 WR("/*    Reverse : FALSE.                                           */\n");
1881
 WR("/*                                                               */\n");
1882
 WR("/* For more information on the Rocksoft^tm Model CRC Algorithm,  */\n");
1883
 WR("/* see the document titled \"A Painless Guide to CRC Error        */\n");
1884
 WR("/* Detection Algorithms\" by Ross Williams                        */\n");
1885
 WR("/* (ross@guest.adelaide.edu.au.). This document is likely to be  */\n");
1886
 WR("/* in the FTP archive \"ftp.adelaide.edu.au/pub/rocksoft\".        */\n");
1887
 WR("/*                                                               */\n");
1888
 WR("/*****************************************************************/\n");
1889
 WR("\n");
1890
 switch (TB_WIDTH)
1891
   {
1892
    case 2: WR("unsigned short crctable[256] =\n{\n"); break;
1893
    case 4: WR("unsigned long  crctable[256] =\n{\n"); break;
1894
    default: chk_err("gentable: TB_WIDTH is invalid.");
1895
   }
1896
 chk_err("");
1897

    
1898
 {
1899
  int i;
1900
  cm_t cm;
1901
  char *form    = (TB_WIDTH==2) ? "0x%04lX" : "0x%08lXL";
1902
  int   perline = (TB_WIDTH==2) ? 8 : 4;
1903

    
1904
  cm.cm_width = TB_WIDTH*8;
1905
  cm.cm_poly  = TB_POLY;
1906
  cm.cm_refin = TB_REVER;
1907

    
1908
  for (i=0; i<256; i++)
1909
    {
1910
     WR(" ");
1911
     WP(form,(ulong) cm_tab(&cm,i));
1912
     if (i != 255) WR(",");
1913
     if (((i+1) % perline) == 0) WR("\n");
1914
     chk_err("");
1915
    }
1916

    
1917
 WR("};\n");
1918
 WR("\n");
1919
 WR("/*****************************************************************/\n");
1920
 WR("/*                   End of CRC Lookup Table                     */\n");
1921
 WR("/*****************************************************************/\n");
1922
 WR("");
1923
 chk_err("");
1924
}
1925
}
1926

    
1927
/******************************************************************************/
1928

    
1929
main ()
1930
{
1931
 printf("\n");
1932
 printf("Rocksoft^tm Model CRC Algorithm Table Generation Program V1.0\n");
1933
 printf("-------------------------------------------------------------\n");
1934
 printf("Output file is \"%s\".\n",TB_FILE);
1935
 chkparam();
1936
 outfile = fopen(TB_FILE,"w"); chk_err("");
1937
 gentable();
1938
 if (fclose(outfile) != 0)
1939
    chk_err("main: Couldn't close output file.");
1940
 printf("\nSUCCESS: The table has been successfully written.\n");
1941
}
1942

    
1943
/******************************************************************************/
1944
/*                             End of crctable.c                              */
1945
/******************************************************************************/
1946

    
1947
20. Summary
1948
-----------
1949
This document has provided a detailed explanation of CRC algorithms
1950
explaining their theory and stepping through increasingly
1951
sophisticated implementations ranging from simple bit shifting through
1952
to byte-at-a-time table-driven implementations. The various
1953
implementations of different CRC algorithms that make them confusing
1954
to deal with have been explained. A parameterized model algorithm has
1955
been described that can be used to precisely define a particular CRC
1956
algorithm, and a reference implementation provided. Finally, a program
1957
to generate CRC tables has been provided.
1958

    
1959
21. Corrections
1960
---------------
1961
If you think that any part of this document is unclear or incorrect,
1962
or have any other information, or suggestions on how this document
1963
could be improved, please context the author. In particular, I would
1964
like to hear from anyone who can provide Rocksoft^tm Model CRC
1965
Algorithm parameters for standard algorithms out there.
1966

    
1967
A. Glossary
1968
-----------
1969
CHECKSUM - A number that has been calculated as a function of some
1970
message. The literal interpretation of this word "Check-Sum" indicates
1971
that the function should involve simply adding up the bytes in the
1972
message. Perhaps this was what early checksums were. Today, however,
1973
although more sophisticated formulae are used, the term "checksum" is
1974
still used.
1975

    
1976
CRC - This stands for "Cyclic Redundancy Code". Whereas the term
1977
"checksum" seems to be used to refer to any non-cryptographic checking
1978
information unit, the term "CRC" seems to be reserved only for
1979
algorithms that are based on the "polynomial" division idea.
1980

    
1981
G - This symbol is used in this document to represent the Poly.
1982

    
1983
MESSAGE - The input data being checksummed. This is usually structured
1984
as a sequence of bytes. Whether the top bit or the bottom bit of each
1985
byte is treated as the most significant or least significant is a
1986
parameter of CRC algorithms.
1987

    
1988
POLY - This is my friendly term for the polynomial of a CRC.
1989

    
1990
POLYNOMIAL - The "polynomial" of a CRC algorithm is simply the divisor
1991
in the division implementing the CRC algorithm.
1992

    
1993
REFLECT - A binary number is reflected by swapping all of its bits
1994
around the central point. For example, 1101 is the reflection of 1011.
1995

    
1996
ROCKSOFT^TM MODEL CRC ALGORITHM - A parameterized algorithm whose
1997
purpose is to act as a solid reference for describing CRC algorithms.
1998
Typically CRC algorithms are specified by quoting a polynomial.
1999
However, in order to construct a precise implementation, one also
2000
needs to know initialization values and so on.
2001

    
2002
WIDTH - The width of a CRC algorithm is the width of its polynomical
2003
minus one. For example, if the polynomial is 11010, the width would be
2004
4 bits. The width is usually set to be a multiple of 8 bits.
2005

    
2006
B. References
2007
-------------
2008
[Griffiths87] Griffiths, G., Carlyle Stones, G., "The Tea-Leaf Reader
2009
Algorithm: An Efficient Implementation of CRC-16 and CRC-32",
2010
Communications of the ACM, 30(7), pp.617-620. Comment: This paper
2011
describes a high-speed table-driven implementation of CRC algorithms.
2012
The technique seems to be a touch messy, and is superceded by the
2013
Sarwete algorithm.
2014

    
2015
[Knuth81] Knuth, D.E., "The Art of Computer Programming", Volume 2:
2016
Seminumerical Algorithms, Section 4.6.
2017

    
2018
[Nelson 91] Nelson, M., "The Data Compression Book", M&T Books, (501
2019
Galveston Drive, Redwood City, CA 94063), 1991, ISBN: 1-55851-214-4.
2020
Comment: If you want to see a real implementation of a real 32-bit
2021
checksum algorithm, look on pages 440, and 446-448.
2022

    
2023
[Sarwate88] Sarwate, D.V., "Computation of Cyclic Redundancy Checks
2024
via Table Look-Up", Communications of the ACM, 31(8), pp.1008-1013.
2025
Comment: This paper describes a high-speed table-driven implementation
2026
for CRC algorithms that is superior to the tea-leaf algorithm.
2027
Although this paper describes the technique used by most modern CRC
2028
implementations, I found the appendix of this paper (where all the
2029
good stuff is) difficult to understand.
2030

    
2031
[Tanenbaum81] Tanenbaum, A.S., "Computer Networks", Prentice Hall,
2032
1981, ISBN: 0-13-164699-0. Comment: Section 3.5.3 on pages 128 to 132
2033
provides a very clear description of CRC codes. However, it does not
2034
describe table-driven implementation techniques.
2035

    
2036

    
2037
C. References I Have Detected But Haven't Yet Sighted
2038
-----------------------------------------------------
2039
Boudreau, Steen, "Cyclic Redundancy Checking by Program," AFIPS
2040
Proceedings, Vol. 39, 1971.
2041

    
2042
Davies, Barber, "Computer Networks and Their Protocols," J. Wiley &
2043
Sons, 1979.
2044

    
2045
Higginson, Kirstein, "On the Computation of Cyclic Redundancy Checks
2046
by Program," The Computer Journal (British), Vol. 16, No. 1, Feb 1973.
2047

    
2048
McNamara, J. E., "Technical Aspects of Data Communication," 2nd
2049
Edition, Digital Press, Bedford, Massachusetts, 1982.
2050

    
2051
Marton and Frambs, "A Cyclic Redundancy Checking (CRC) Algorithm,"
2052
Honeywell Computer Journal, Vol. 5, No. 3, 1971.
2053

    
2054
Nelson M., "File verification using CRC", Dr Dobbs Journal, May 1992,
2055
pp.64-67.
2056

    
2057
Ramabadran T.V., Gaitonde S.S., "A tutorial on CRC computations", IEEE
2058
Micro, Aug 1988.
2059

    
2060
Schwaderer W.D., "CRC Calculation", April 85 PC Tech Journal,
2061
pp.118-133.
2062

    
2063
Ward R.K, Tabandeh M., "Error Correction and Detection, A Geometric
2064
Approach" The Computer Journal, Vol. 27, No. 3, 1984, pp.246-253.
2065

    
2066
Wecker, S., "A Table-Lookup Algorithm for Software Computation of
2067
Cyclic Redundancy Check (CRC)," Digital Equipment Corporation
2068
memorandum, 1974.
2069

    
2070
--<End of Document>--