0% found this document useful (0 votes)
201 views17 pages

JCrenshaw ImplementingCRCs

The document discusses cyclic redundancy checks (CRCs), which are a popular error-detection method. CRCs work by appending a checksum calculated from the message to the message itself, allowing the recipient to check for errors. While simple techniques like parity bits are easy to implement but not very reliable, CRCs can reliably detect both single-bit errors and burst errors through the use of a carefully designed algorithm.

Uploaded by

spyeagle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
201 views17 pages

JCrenshaw ImplementingCRCs

The document discusses cyclic redundancy checks (CRCs), which are a popular error-detection method. CRCs work by appending a checksum calculated from the message to the message itself, allowing the recipient to check for errors. While simple techniques like parity bits are easy to implement but not very reliable, CRCs can reliably detect both single-bit errors and burst errors through the use of a carefully designed algorithm.

Uploaded by

spyeagle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

)Implementing GRGs

t an unrecorded event

A
lost in the mists of time,
a caveman named Og
sent a message propos- Most of you have
ing peace, via smoke
,ignal. to the signal officer of the neigh- already heard of
boring tribe. Unfortunately, a gust of
~ ind disrupted the pattern of a particu- the CRC, and
htrly important part of the message, and
the message was misunderstood. Sadly, you've almost
Og's tribe was wiped out.
Ever since then, people have been certainly used it,
sending messages by methods ranging
from smoke signals to laser beams to whether you are
spread-spectrum communications sat-
ellites, and messages have been arriving aware of it or not.
garbled, with more or less disastrous re-
sults. It's not surprising, then, that peo- We'll begin with some background as to
ple have long sought ways to make sure the motivation and power of the CRC,
that their messages were received prop- then continue on to the gory details. I'll
erly. Lots of methods have been tried spend just enough time discussing poly-
over the years. nomials to convince you that they're not
Today, one of the most effective and needed, and then we'll get on to some
popular error-detection methods is the efficient code implementations. I'll also
cyclic redundancy check (CRC). It's discuss some of the gotchas you should
used in virtually every field where trans- beware of.
mitting serial data is involved. It's even With any kind of luck and some per-
built into your disk-drive controller. sistence on your part, you'll leave this
Most of you have already heard of the article with a real understanding of how
CRC, and you've almost certainly used and why the CRC works. At the very
it. whether you are aware of it or not. least, you should be able to say, "Search
Though ubiquitious, the CRC algo- me. I just copied it from Crenshaw.~
rithm is surrounded by an inordinate
amount of fog. We can't even seem to SOME BACKGROUND
agree on what the acronym stands for ver since the landmark Og af-
(some say it's cyclic redundancy code).
Ask hardware people how it works, and
they're likely to say, "It's done with shift
E fair, people have been seeking
ways to make sure that their
messages get across without being mis-
registers and exclusive-OR gates." Ask understood. In today's information age,
mathematicians, and they'll say, "It's that's more important than ever. We
done using a polynomial division, mod- can accomplish this goal in many ways,
ulo two, with the generating polynomial but they all boil down to these three
chosen from a closed Galois field." (Oh. requirements:
Thank you very much. That clears ev-
erything right up.) Ask honest software • Along with the message, provide the
types, and they'll tell you, "Search me recipient with some way to know if it got
how it works. I just copied it from the there correctly.
XMODEM code." • The recipient should send a return
[n this article, I'm going to try to cut message, acknowledging receipt or ask-
through some of that obscuring fog. ing for a retry.
• Continue to send the message until it magic decoder rings to the body of the
gets to its destination ungarbled. message, and compare the result to the
code that was received. If they don't
Effective data transmission involves match, the message must be in error. To
two aspects: error detection and error be efficient, the code should be small
transmission. The CRC is an error de- compared to the message body. or
tection mechanism. Yes, I know that course, the smaller the code. the more
some error detection and correction the possibility of aliasing, where t\\()
methods such as the Hamming codes different messages can generate the
exist, but today, almost everyone still same code. But with modern methods
separates the two aspects and counts on such as the CRC, this scenario is ex-
retransmission for the correction half of tremely unlikely, as we shall see.
the system. The smallest code is a single bit.
How can the recipient of a message That's the idea behind the parity bit,
tell whether it's been garbled? The most which is a measure of the number of
obvious way is to send every message ones in the message's binary represen ta-
twice. But that method involves a lot of tion-zero for an even number, one for
overhead-at least double the trans- an odd number. Since it's short, it's also
mission time; much more if the error easy to get aliasing, so parity bits only
rate is high enough so that errors are work for very small message blocks
likely. And that's bad. Time is money. -typically one byte.
We can make things a little better by Another choice is the checksum. It's
splitting the message up into smaller a popular one, because it's so easy to
blocks, and seeking confirmation on understand and compute. We simply
each block. This way, we don't have to add all the bytes in the message as
retransmit the whole message, but only though they were binary numbers (ig-
the blocks that were garbled. But we're noring carries). Typically, the resulting
still limited to a minimum of twice the sum is appended to the message as its
transmission time. What we really need twos complement, so that the recipient.
is a method to test the message for cor- adding the same characters plus the
rectness, without using many bits of the checksum, should get zero. Intel hex
message. and Motorola S-record formats use ei-
Of course, the ancient kings knew ther a 1- or 2-byte checksum.
how to authenticate messages. They Finally, we have the CRe. As nearly
used a courier and sealed the messages as I can tell, it arrived on the scene in
with their private seal, carefully mono- 1961. The idea behind it is exac{ ir the
grammed to discourage forgery. No one same as for the checksum: compute <.l 1-
could tamper with the message without to-4-byte BCC, calculated from the
breaking the seal. We can't do that with message body, and append it to the mes-
messages that are sent electronically, sage. The only difference is the algo-
but we can steal the general idea. You rithm embodied in the magic dccoder
append some kind of code to the mes- ring.
sage that's virtually certain to be al-
tered if the message is tampered with or WHY USE A CRC?
otherwise garbled. little reflection should con-
Early on, someone got the idea to use
a code (sometimes called the block-
check code, or BCC) that could some-
A vince you that the reliability of
any error-detection 1l1\,;c...ha-

nism (due to aliasing) is a function of


how be computed from the body of the the size of the appended code. An N-bit
message. The recipients apply their code can only have 2N unique values. A
Implementing
eKes
single parity bit can only detect single
(or any odd number of) bit errors. If the
likelihood of multiple errors is low, it
works fine. But if it's high, there's only a The CRC is equally
50% chance that a parity bit will reflect
the error. valid for small and
Similarly. a checksum or CRC of
eight bits (one byte) can have only 256 large messages,
possible values, which means that, on a
statistical basis, we have a 0.4% chance which is why it is
that a bogus message will slip through.
Inversely, the reliability of the error-de- so popular and
tection mechanism is 99.6%. For two
bytes, the value is 99.9985%. Now, if the considered worth
CRC also uses two bytes, you might
think that it can't possibly be better the extra
than a checksum. So why bother with
the more complex algorithm? computation
That assumption would be true if
transmission errors were truly random, required.
but they're not. In the real world, two
kinds of errors typically occur: random- the BCC, so the probability of two off-
bit errors and burst errors (in which sev- setting errors is virtually nil. In that
eral adjacent bits are garbled). The sense, the CRC for a message is a bit
CRC shines in catching these two er- likea hologram ofa scene: the bits ofthe
ror.,. Given the proper choice of algo- data are scattered through all the bits of
rithm. a 16-bit CRC can detect: the BCe. For the same reason, the CRC
is equally valid for small messages as for
• 100% of all single-bit errors large ones. That's the reason the CRC
• 100"e of all two-bit errors method is so popular and considered
• I00'"6 of all odd numbers of errors worth the extra computation required.
• I00',; of all burst errors less than 17
bit'>v. ide CLEARING THE FOG
hen I first asked someone to

W
• 99.9969% of all bursts 17 bits wide
.99.9985% of all bursts wider than 17 explain the CRC to me, I
bit'>(the same as a checksum) was told, "It's the remain-
der of a polynomial division, modulo
I-ur extreme reliability, using 32 bits two." I was then given the generating
improves this performance even more, polynomial:
by five orders of magnitude! Those stat-
istics are pretty impressive, which is
\\ hat makes the CRC so popular.
The nature of the checksum is such Huh? What the heck does that mean?
that errors tend to be localized, some- And what is x, anyway? A data bit?
times changing only a single bit. Offset- Shall I give it a value?
ting or systematic errors (say, a stuck A more meaningful way to under-
bit on the UART) can often be missed. stand what's going on with CRCs must
B) contrast. any error in tHe message exist. It's easier if we first digress into
4uid,l:- propagates into all the bits of the related field of psuedo-random
numbers. Let's playa little game, of the It is a shift register, with one exclusive-
kind'often seen in I.Q. tests or math puz- ORgate added. Place any number in the
zle books. Look at this a sequence of sequence into the bits of this register,
numbers: mentally cycle it, and you will soon con-
vince yourself that it does indeed gener-
ate the IS-number sequence. It's a
source of psuedo-random numbers, bet-
Quick! What's the next number in the ter known as white noise, and you'll find
sequence? one in every Nintendo game. Of course,
in the real world, these generators use
If you didn't say 15, please move on to more than four bits. In general, an N-bit
the next article. This one's not for you. psuedo-random number generator can
For the rest of you, please give me the generate 2N-1 unique numbers before
next number in this sequence: repeating. The -1 is there because we
can't allow the value zero. If the gener-
ator ever gets all zero bits, no feedback
can occur, so it will remain at zero. Un-
Not so easy, is it? (The answer is one.) fortunately, not just any old set of feed-
It's not supposed to be easy, because the back ta ps (the exc1usive-OR ga tes) wiII
second sequence is a set of what are do. For example, if the gate were at Bit I
called pseudo-random numbers. The instead of Bit 0, we would end up with
"psuedo" part is because they are not three shorter sequences:
really random. The sequence will repeat
over and over forever. But by every oth- a.l,10,5,8,4,2
er measure of randomness you care to b.3, 11, 15, 13, 12,6
apply (average, standard deviation, and c. 7,9,14
so on), the sequence is random. Hence
the name. The sequence covers all the 4- Now, you begin to see the tricky part
bit integers, except zero. about this process. We want a maxi-
How did we get this sequence? In mal-length sequence, and to do get it,
this case, the magic decoder ring is a the taps must be carefully chosen. And
hardware circuit, as shown in Figure 1. that's where the polynomials come in.

Figure 1
A hardware circuit.
Implementing
eRes For a maximal-
length pseudo-
random number
We look for factors of polynomials the
sequence, you same way as with integers: by trial and
POLY-CONfUSED error, using division. We learned poly-
y foray into the theory be- need a polynomial nomial division (sometimes called syn-

M hind all this stuff led me


deep into the bowels of group
theory. I learned more than I care to
that's irreducible.
thetic division) in algebra class (re-
member?). It's much like ordinary
division, except that you have to write
know about Abelian groups and Galois It's the polynomial the polynomials with the highest order
fields. I sure won't burden you with all first, and use only the first terms in the
that stufr. You need only know that it's equivalent of a divisor and dividend. If, for example,
this theory that leads us into polynomi- the highest order term in the dividend is
als and polynomial division. It turns out prime number. x3 and the divisor is x, the first term in
that, for a maximal-length pseudo-ran- the quotient has to bex'. From there, it's
dom number sequence, you need a poly- concept is straightforward. much like ordinary division: multiply,
nomial that's irreducible (one that can- In the normal world of polynomials subtract, and bring down the remain-
not be factored). It's the polynomial (not modulo two), the polynomial: der. If the remainder is zero, the divi-
equivalent of a prime number. Finding dend is reducible.
them is not easy. It's as hard as finding a The polynomial arithmetic used for
large prime number, and complicated CRC theory is a little different. It uses
by the harder division process, but the modulo-two arithmetic. The reason is

CROSS DEVELOPMENT SYSTEMS


modulo two, addition and subtraction = 0, not 2), so the only coefficients poly-

Implementing are the same.


Already, we've cleared out one fog
nomials can have are zero or one. Poly-
nomial division in modulo two is as easy
as it is in ordinary arithmetic, once you
CKCs factor. The next time someone says
"modulo-two arithmetic," just think
"exclusive OR." Simple. Also, in this
get used to the new rules. An example is
shown in Figure 2.
world twos and threes don't exist (1 1 + It looks straightforward, but writing

simple: ordinary arithmetic doesn't per-


mit the group properties that the math-
Figure 2
Modulo 2 dIvisIon.
ematicians need for their powerful
x' + x + 1
methods to work.
In modulo-two arithmetic, we don't x' + x + I ) x' + x' + 1
have carries or borrows from any bit po- x' + x' + x'
sitions. The rules for adding two bits
are: x' + 1 Here's enlighte
x' + x' + x platforms for ind
applications.
0+0=0
There's a platf~
0+1=1 x' + x + 1
combines the adv
1+0=1 x' + x + 1 industry leaders .
1+1=0 and Intel.
Intel is well·knol
Look familiar? It is also the truth table embedded control
for a simple half-adder, or exclusive-OR. microprocessors. '
As it turns out, subtraction gives the performance, desi
quality represent I
same rules, so in this funny world of
And among InteI'i
products for indm
/:;~.:\, .
.. " ...
the new 302i rack·
:S~'fh,eToughest80S,1>J«?bs Just Got Easier!' range of Inte1386T1
platrorms, and so(,
~.f-:'~' such as iRMX®fo
for 8051 desigiwI:s i~ to sqllee~e all the performallce out of the ~051
I .. . , , ' .~ , ' " , . , ' '

.. '::~~'~,T~leclzallellge Hamilton!Avnet 0
~11;~~tt1,~ lowest cost, alld Frallkllll IS,tf',~rF:.wg~I,"9~'fQols t~lat IlClp YOll meet It." systems engineerin
our extensive valm
capabilities.
:-ranklin Introduces 8051 "e" Introducing RTX -51 Operating System!
It's the first real time multi-tasker designed specially for
Put them all toget
result is superior Sl
Professional Developers Kit! the 8051. RTX-51 is very small, as little as 800 bytes for
code, so it works even on single chip versions of the 8051.
Hamilton! Avnet 1II
building a reputatil
And task switches are very fast! With a full set of as fea- So see the differenc
landle Bigger Jobs. tures, and support for all 8051 variants, RTX-51 opens up For details, call Hal
)ur Best in the Industry "C" compiler now supports new vistas for 8051 development! free, 1 (800) 442-64!
llulti-tasking and bank switching with up to 16 banks of
temory for code and data. No other bank management Move up to the Professional Developers Kit!
:heme is as code and execution time efficient. Call (408) 296-8051 or FAX us at (408) 296-8061
for your FREE evaluation package!
'he Fastest Just Got Faster.
v'ith all its new features, the C-51 Compiler is IARlArchlrnede.
FRANKUN BSOI
ill the fastest, most code efficient "C' PROFESSIONAL TASKING 1CC8051
8,753
Jmpiler available. And for big jobs, C-51 Total Execution Time
(large model)
6.744s9C
8.287 see 10,98
8,388
17,295
. faster than ever for both compile and Module Code Size 188 bytes 266 238
(large model) 188by1es 303 343
xecute times! dYNlmlc Datil Sin 41 bytes 126 96
Total Code Size 1223 bylas 1936 1626

.-
(large model) 1292 bytes 3467 2088

WhetstoneSlSecond
Ohryatonel!Second
13
--,., 3
203 163 90

CIRCLE # 13 ON READER SERVICE CARD

24 EMBEDDED SYSTEMS PROGRAMMING JANUARY 1992


Implementing Yes,
Figure 4 j
CKCs Three representations of a hardware circuit.

Figure 3
The easy way.

111

111 )10101 Generating Polynomial = x4 + x3 + I


111 Feedback factor = 1001 b

down all those polynomial terms gets form. Looks a lot easier, doesn't it? In
tedious, especially if we're talking about fact, it's simply binary division, but us-
16th-order polynomials! Fortunately, ing exclusive ORsinstead of subtraction.
once I'd done this problem a few times, I Since it's binary, of course, you don't
finally figured out that it's not neces- really need to perform a multiplication.
sary to write the xs down at all A t each step, we either su btractthe divi-
-just the coefficients. Figure 3 shows sor or we don't. We don't need to com-
the same division in this simplified pare the two terms (we don't worry if
one polynomial is bigger than the other.
Since addition and subtraction are the
same, the concept of "bigger" does not
On Target with Turbo Debug! exist). We only have to look at the lead-
ing terms. If they have the same order,
we subtract. YOl
Now, we get rid of the second fog corrun
factor. From now on, when someone solvinf
starts talking to you about polynomial
division, you will know that what they
embed
really mean is ordinary binary division proble:
-modulo two. HUI
In Figure 3, each product to be sub-
tracted is written down one place to the
money
right, which is equivalent to shifting the neers n
dividend to the left. So, what we're real- worke<
ly talking about is shifting, then sub- scale p:
tracting (or exclusive OR-ing)a constant
Place your Microsoft or Borland C Code in the target system and debug value. But that's exactly what's going on
it often
it as it runs with Datalight's C_thru_ROM ... in Figure I. The operations are entii'Cly of the r
C _thru _ROM eases ROM development with all versions of Borland-C, C++. and Micro-
soft C. New features include Turbo Debug support and remote debugging via a ROM socket.
equivalent. today's
We only have a couple of annoying,
C _thru _ROM is a complete ROM development package that works with your choice of
compiler to quickly get your application running in ROM. Includes: full 80x86 locator but minor, complications. First, the
and 32-
which outputs in Intel OMF, hex, and binary; ROMabie startup code; remote debugging via shift register shifts right, while the divi- AtA
Turbo remote debugger or Code View-like debugger; full floating point support; ROMabie
library (prinrj, mal/oc, etc.); and much more. Call, write, or fax today for full details.
sion operation shifts the dividend left. we're h
We'll just have to remember to reverse
Free Demo Disk! Call Today Toll-Free 1-800-221-6630 the bit order.
hardw2
Second, the division subtracts first, betterE
and then shifts for the next round. In the
17455 68th Ave NE. Suite 304. Bothell, WA 98011, USA· 206-486-8086' fax 206-486-0253 shift register, we look at the least signifi- In the u.s. and C
44-(O}~2S16
CIRCLE # 15 ON READER SERVICE CARD
cant bit (LSB) shift, then perform the tact Appllt.'d Micro
regiSiered lndema
responds to the lowest-order term in the
Implementing polynomial; that is, XO or one. The three
representations are shown together in

eRes You might well ask


why I even bother
Figure 4 (p.26). I advise you to cherish
this figure. You will rarely see all three
representations identified on the same
figure, so it is literally a rosetta stone.
mentioning With it, you need never be confused by
polynomials again.
polynomials, with You might well ask why I even both-
exclusive OR.The divisor is shifted one er mentioning polynomials, with their
bit relative to its equivalent polynomial. their awkward awkward representation and built-in
It may not seem so, but at this point confusion factor. Good question. I wish
the fog is almost completely dissipated. representation I had a good answer. Tradition seems to
We now have a "rosetta stone" that lets be the only reason. The polynomial rep-
us translate between the three represen- and built-in resentation is good if you have to deal
tations. Consider, for example, the with the field theory to indentify a good
polynomial: confusion factor. polynomial. For the rest of us, it's com-
pletely unnecessary, and only generates
To get the equivalent shift register, fog. Give me the feedback factor, or bet-
we first turn the number around, then ter yet, the whole equivalent circuit. But
In the binary form needed to do a divi- shift it right one place, to get I00 I, This don't be surprised when others give you
sion, this polynomial is 11001. The number is the feedback factor that the polynomial form, because that's the
number has a one bit for every non-zero drives the generator. Place a tap at the way CRCs are normally defined.
term, starting with the highest order entrance to every bit that has a one in its
(the highest and lowest bits will always feedback factor. ONTOTHECRC
be ones, by the way, for any useful Alternatively, just remember that f course, the circuit shown in
polynomial.) the left-hand bit of the shift register cor-
O Figure I is not a CRC gener-
ator, just a pseudo-random
number generator. It cycles constantly,
unchanged, because it doesn't recieve
input. That's easy to fix, though.
Remember that our pseudo-random
number generator cannot deal with
zero? That bothers some people, since
clearing all the bits of a shift register is a
common thing to do. The problem is
easily fixed by inverting the output,
which will still give us a maximal-
length sequence, just a different one:

GOFAST'" Now we can have a zero, but not a 14.


No help for that.
lightning-Fast Floating Point Accelerators Next, let's get fancy. Suppose we re-

E Illpoweryour 80x86applications with


GOFASTaccelerators. Fast, reentrant,
and ROMable,GOFASTaccelerators boost
GOFAST IEEE accelerators are opti-
mized for 8051,8096,8086,80386, i960,
6801, 6809, 68HCII, 68xxx, 80S5, Z80,
place the inverter at the output by one
more exclusive-OR ga te (the missing one
at x'), and let the data diddle it high and
peltormance and make sure you can em- R3000 and more. low. Boy, that should really confuse
bed your application. Call for your free GOFAST infonnation things!
Link and go with c: Microsoft®, Bor- diskette today: 503-641-8446; FAX 503- But that's precisely the concept be-
land"),Intel"',MetaWare®,and WATCOM®. 644-2413; SOO·356·7097. hind the CRC algorithm. The idea is to
Dynamically replace 8Ox87coprocessors
get the effect of the data bits widely
dUlingexecution.
~ 14215 NW Science Park Drive scattered throughout the BCC, which is
, 1991 us Software Corporation, GOFAST and DynaCOP are
tr'aden1<:'lrks of US Software Corporation. All other trademarks
I.D Portland. OR 97229 what all those taps do.
beiong to their respectwe owners.
'i'iiIr U S SCPTW"AAE® With that long buildup, we're now
poised to look at true CRCs in all their
glory. The most popular standards are
shown in Figure 5 (p,43). The CCITT much obsolete, and the CRC-12 is only to get optimal error-detection out of the
algorithm is the international standard. used when bytes arc six bits. system. Don't worry about how the) do
The CRC-16 is most often used in the As you can see, real CRCs differ it. Better them than us.
United States. The CRC-8 is pretty from our toy one only in the number of I should mention a few points about
bits-the concept is the same. For the how the data gets handled. From a
record, however, the criteria for the gen- mathematician's point of vicw. thc cn-
erating polynomial (feedback factor, tire message is considered to be a string
for those of us in the know) is different. of bits, each bit corresponding to a term
Listing 1 Rather surprisingly, the CRC gener- in a humongous polynomial. So, from
The Serlal_ eRe program.
ators do not generate maximal-length their point of view, we are dividing one
sequences. In fact, the polynomials are long polynomial by another one. The
deliberately chosen to be reducible by BCC is the remainder. From our point
the factor x + I, because that happens of view, we are dividing two binary num-
const Feedback = $8408: 1 CRC-CCITT I to eliminate all odd-bit errors. The fact bers. In the real world, though. we know
1 SA001: CRC-16 I is, the polynomials are carefully tailored we're really sending messages a byte at
I $8000: LRCC-16 I

Procedure UpdateCRC(B, Byte);


var 1: Integer:
begin
for i ,= 1 to 8 do begin
if Odd(B) Xor Odd(CRC) then
CRC ,= (CRC Shr 1) Xor Feedback
else
CRC ,= CRC Shr 1:
B ,= B Shr 1:
end:
end:

Procedure SendString(S, String): .


, ,- .. I J<. "IF'.' '* .,.- •
YOll can stan your ebuggln With this FREE demo simulatOr. You can load up
var 1: Integer:
to 512 bytes of code, assembler, C, or PL/Mand do full debugging/si
begin In assembly and source level, A great way to get Started for FREE.
for 1 ,= 1 to Length(S) do Fantastic f01 schoolsl Just call and we'll send It!
UpdateCRC(Ord(S[llll ;
Fl1 "'') f 17 ~ I
---'
Th& full-blown simulator Is an extension of
the DEMO. You can load up to 64K of
code and use 64K of XDATA space. You
can program an "external environment"
to interact with your code to simulate your
Procedure sendMessage(S, StrIng): target system, The emulator is the hard-
var OldCRC, Word: ware extension of the simulatorl
begIn
CRC ,= 0:
The 30MHz real-time emulator has been
SendStrlng(S) ; the industry standard for years. With its
OldCRC ,. CRC: complex breakpoint logic and advanced
trace, nobody can beat it for performance,
Write('CRC Computed Is '):
Plug-in or RS-232 configuration. All 8051
WordLn(CRC) : derivatives are supported!
UpdateCRC (OldCRC) :
call Nohau's24-hou
UpdateCRC(OldCRC Shr 8):
end: nOHau
CORPORATION
informationcenterto
receiveinfoon your
FAX 408-378-2912
begIn 51 E. Campbell Avenue, Campbell, CA 95008
(408)866-1820 FAX(408)378·7869
SendMessage(' THE.QUICK.BROWN.FOX.0123456789' ):
WordLn(CRC) : Australia (02) 654 1873, Austria (0222) 38 76 38, Senelux +31 1858·16133, Canada (514) 689·5889,
Czechoslovakia 0202·2683, Denmark (42) 65 81 11, Finland 90·4521255. France (01)·69 412801. Germany
ReadLn; 08131·25083. Great Srltain 0962·73 31 40. Greece 01·862·9901. Hungary (1) 117 6576, Israel (03) 48 48
32. Italy (011) 771 00 10. Korea (02) 784 784 1. New Zealand (09) 392·464. Portugal 01·80 9518, Norway
end. 02·649050. Singapore (065) 264-6077, Spain (93) 2172340. Sweden 04D-9224 25. Switzerland (01) 740 41 05
Taiwan (02) 7640215. Thailand (02) 281·9596. Yugoslavia 061 621066.

CIRCLE # 20 ON READER SERVICE CARD


a time, and the standard convention for sage that the recipient has received. At send the BCe. As the LSB of the Bee
all data transmission is to send the least this point, the contents of our BCC reg- arrives at the input, it should match the
significant bit (LSB) first. It makes isters should match. Now, we have to bit in the recipient's register, so the ex-
sense, then, to think of the LSB of the
first byte as the most significant bit
(MSB) of the long binary number that
we're going to divide (or, equivalently,
the highest-order term in the polynomi-
Table 1
Test-case data.
al), That's the reason for the relation-
ship between bit patterns and polynomi- Data string CCITT SDLC CRC16 XMODEM
al terms. It's confusing, because not
onl}!are these two items in opposite or- 'M' 99E1 9666 35CO 9969
ders, but if we want to perform the divi- 'T' 14A1 1B26 FF01 1A71
sion by hand (as a sanity check, for ex- 'THE' 7080 44BE 23B6 1EOA
ample), we have to invert the bits of 'THE,QUICK,BROWN,FOX,0123456789' 70C5 OF91 B96E 0498
every byte transmitted.
To drive home that point, let's actu-
ally perform such a division. The pro- 68331, 68332, 68340 Developers:
cess is shown in Figure 6 (pAO). I've
used a single-byte message, the ASCII Don't Ignore .
lIs. character M. We'll use the CCIIT
code. To perform the division, we must
append 16 zeros to the message. After Background Mode!
all, the dividend has to be larger than
the divisor! This step is not required If you're ignoring Background Mode, Real-time Simulation.
:lizir when we do the CRC in hardware (or you're ignoring price/performance, To get a head start on your softwarL'.
rRA- software). The circuitry takes care of ease-of-use, and non-intrusiveness the EST Series 300 builds in a CPU32
I in your debugging system. controller and 128K of simul,ltion
that.
RAM. Or. our Background ModL'
Please follow along with this exer-
Motorola Doesn't. system works with your EVS
cise. I know it's painful, but it will re- board. right out of the bo'\.
Motorola realized the benefits
move all the mystery of the process, The of on-chip debugging.That's
polynomial is 17 bits long, so it leaves a why they designed Back- C Source Level
remainder of 16 bits, as needed. We ground Mode into eVL'ry
Debugging.
don't have to check to see if one term is CPU32 microcon-
I EST has portl'd
larger than the other. Since addition is troller.
Intermetrics'
the same as subtraction in this number XD1350
system, the concept of "larger," except Introducing tll thL'
as it refers to the number of bits, does the EST Series 300.
not exist. We look only at the leading bit Series 300! XDB deli\'l'rs
(l prO\·L'11
of each number, lining them up so The EST Series 300
\-\'indl)\'\'l'd
they'll cancel, which corresponds exact- controls your CPU32
target exclusively through interface. compktl'
ly to the hardware implementation,
a 5 MHZ Background Mode source and symbolic
where the exclusive OR is done strictly on information. C level tr,King.
link. It's completely non-intrusive,
the basis of the two leading (rightmost) and powerful m,Knls.
since it doesn't require your target's
bits. RAM. ROM. interrupts, or serial port.
Try Background Mode.
GmlNG THE MESSAGE ACROSS Packed with Just call us. and we'll sL'nd VllU o1n
nce we have the BCC, what do EST Series 300 for a free 1-1dav tri,)!.

O we do with it? The answer, of


course, is to transmit it, since
that's the mechanism the recipient uses
Debugging Power.
Of course, the EST series 300 delivers
the features you need: simple and
conditional breakpoints on RAMI
No obligation. No Risk.

(617) 828-5588
to make sure the message is 0, K. ROM, datil breilkpoints. stepping.
Remember that when a checksum
(rather than CRC) is used, we usually
tracing. view Imodify registers and
memory, and system diagnostics,
at a fraction of the price of a full -
Embedded
Support
Tools Corp.
III
Wilfii.iili.iWyQv I
transmit its twos complement, so the fi-
blown ICE.
nal sum is zero for an error-free mes-
sage. The CRC works in a similar way,
337
though we don't even have to comple-
ODS ment. Suppose that we've sent a mes-
~uipment
IC.,
l6-bit CRCs is the tap positions, which
Implementing are embodied in the variable FeedBack.
The SendString procedure sends a
We're not really
CKCs sending the
string of bytes. The SendMessageproce-
dure initializes the BCC and sends its
final value. We have to save the value,
since it will continue to be updated as its
message value is sent.
We're not really sending the mes-
anywhere, so I sage anywhere, so I added a little debug
clusive ORis zero. Nothing gets fed back output to give the value of the computed
during the shift. If no errors have oc- added a little CRe. The final value printed should al-
curred, the same will be true for every ways be zero.
succeeding bit. Nodata is ever fed back, debug output to By the way, one of the things sorely
so the BCC just gets shifted out, leaving needed in working with this algorithm is
a zero value. In this case, zero is the give the value of some test-case data. Fortunately, Greg
winning score! Morse was kind enough to give us some
the computed CRC. test cases, which I've supplemented a
PROGRAMMERS DO IT IN SOFTWARE bit in Table I (p.33). They're an invalu-
P until now, I've emphasized ing I (p.31), written in Turbo Pascal. able aid for debugging.

U the hardware aspects of the


CRC generator. As a matter
of fact, that's the way the CRC was ori-
The bit-by-bit update of the shift regis-
ter is done verbatim by procedure Upda-
teCRC.As you can see, it's pretty simple
A TABLE-DRIVEN eRe
he verbatim, bit-by-bit algo-
ginally used. Today, it's very often done
in software, which will be our focus for
the remainder of this article.
stuff. Following the circuit exactly, we
exclusive ORthe low-order bits of the
BCC and data, and use the result to de-
T rithm gets the job done and is
fine for most applications. But
it turns out that we have a better, and
A straightforward translation of the cide whether or not to feed back into the much faster, algorithm. Since we're
algorithm to software is shown in List- taps. The only difference between these really sending stuff in bytes rather than
bits, wouldn't it be nice if we could gen-
erate the new BCC for a byte in one
step? Because of the M ixMaster nature
of the CRC algorithm, it's certainly not

Listing 2
A table-driven algorithm.

: Initialize the CRC Table for a bytewise CRC.


This procedure works for any CRC cOde. if
ProcessByte is adjusted as needed.

Procedure MakeTable;
var L Integer;
begin
for 1 ;" 0 to 255 do begin
CRC ;= 0;
ProcessByte(i) ;
Table[i) ;" CRC;
end;
end;

, Send a single byte using table-


driven algorithm

Procedure SendByte(B; Byte);


begin
CRC ;= (CRC Shr 8) Xor Table[B Xor Lo(CRC));
end;
obvious that we can. To see how it's pos-
sible requires one last exercise in pain.
Let's try to follow the progress of an
arbitrary byte through the system. Just
prior to the first shift, the LSBs of the
BCC and the data byte are available at
the inputs to the tap. If we define:

where LaCe) is the low byte of the BCC,


then this value will be the LSB of X, say
Xo. A.s the data is shifted, Xo will be fed
into every stage that has a tap. In any
given stage, all the terms in a given col-
umn are to be exclusive ORedtogether.
This same process takes place for ev-
ery bit transmitted. The final state of
the register after the eighth shift is
eature
rface that
mouse
'ich
means Listing 3
Bytewise table generation.
now
I This procedure creates
the table for a byte.1se CRC. The
ovith algorithm is spec1f1c to the CCITT
~Iowand CRC. Other codes can be done in a
:Jklet that s1ml1ar Manner.
III us at Procedure MakeTable;
lave you var 1: Integer;
z: Byte;
begin
for 1 :' 0 to 255 do begin
z :' 1 Xor (1 Shl 4);
lRE Table[1] ;' (z Shl 8)
Xor (z Shl 3) Xor (z Shr 4);
end;
'100
end;
fj09

'0
Affordable Pe ormance
for the 64180 & Z180
Listing 4 Price and performance are no programs that mysteriously "wander
Bjtewlse clIc without a table. longer mutually exclusive. Softaid's off." In C or assembly, the UEM
I This Procedure PernUs Byte.1se 8-bit UEM Emulators find bugs fast. automatically tracks the MMU.
CRCWithout the Need for a table. The 'table
And only Softaid has the Fiber-Optic Collect real-time trace data with
Link that reduces download time to pre, post, or center triggers. Display it
entry" is bul1t 'on the fly" Note that the
virtually zero. Spend a lot r-P-ro-c-e-s-s-o-r--S--d-' in C source or
algor1ttll is spec1f1c to the CCITYCRC. less time waiting, and a lot pee intermixed with the
Other codes can be done in s1Ml1ar I18nner, l more time debugging. 64180 10MHz disassembled trace
All of Softaid's UEM data. Or, use your own
Emulators include built-in 641808 10MHz clock to collect logic
JOklet Procedure UpdateCRC(B: 8yte);
'(be 386", performance analysis and ..,cZ:1=8:l10B::IlIllZ:J1EOsz::M:lHczd analyzer data.
begin a source-level debugger Is there a better
8 :" 8 Xor Lo(CRC); for C, C++ and PUM. Our real-time solution than Softaid? At $5.495,this
Memory Access Monitor instantly may be the best 8-bits of advice you
8 :·8 Xor (8 Shl 4);
captures "stack creep" and those ever get,
CRC :' (CRCShr 8) Xor (B Shl 8) Xor
(8 Shl 3) Xor (8 Shr 4);
end;
8300 Guilford Rd.• Columbia, MD 21046
(800) 433-8812' FAX: (301) 381-3253
"OFIAID, Inc.
--J
CIRCLE # 26 ON READER SERVICE CARD
shown in Figure 7 (p.44). The dotted
line is to emphasize that the resulting
BCC really consists of two parts:

• The high byte of the original BCC,


shifted down into the low-byte position .
• The rest of the result, which depends
only on the value of X.

Now, whatever value X has, it is, after


all, only a byte, so it can only take on 256
po~ible values, which suggests that we
can precompute the value and store it in
lMHz a table. The table, of course, is constant,
neously so it can be precomputed at initializa-
alysis

Listing 5
The XMOD~ algorithm.
STOP WASTING
{ The XMODEMAlgor1thll shUts left TIME & MONEY
<\ND, { instead of right. This impacts most of the BSO/TASKING'S new toolkit
{ procedures. for developingsoftware for
NT, the 68000 family,called
TAsKTOOLS~, beats all others
on the market today. Check out
these features and benefits.
for Procedure Send8yte(B, Byte): CCOMPILER
lIyzer begin •ANSIC
CRC := (CRC Shl 8) Xor Table[B Xor H1(CRCl]: •Highly optimized code
rs
·Reentrant code
a end:
•Direct control of I/O BENEFITS
·Interrupt handlers may be TAsKTOOLS~ offersyou the
written in C followingbenefits:
·Floatingpoint support ·Reduced code size
Procedure NakeTable, ·68040and 68332 support ·Increasedproductivity
var 1: Integer: CROSSVIEW~ DEBUGGER ·Great documentation
z: Byte, ·All major emulators supported •Hot line support
begin ·Multi-window interface • For PC, Sun, Vax,HP,Apollo,
•Code & data breakpoints ffiM&DECRISC
for 1 :" D to 255 do begin •Multi object formats
• Sourcelevel tracing
z :" 1 Xor (1 Shr 4),
·Stack tracing OTHER PROCESSORS
Table[1] := z Xor (z Shl 5) Xor (z Shl 12), ·I/O simulation WITH SIMILAR SUPPORT
end: ·Motorola 68HClJ
AsSEMBLER &. LINKER
end:
·Motorola compatible ·Intel80X86
·FPU & MMU support •Intel 8051& derivatives
{ Message Protocol for XMODEM.Note the two ·Fully featured •TMS32OC25
{ null bytes. and the way the BCC is sent.
·Siemens 80Cl66
CALLUS
1-8llO-458·8276.
Procedure SendMessage(S, String): Outside U.S.A.617-894-7800.
var OldCRC: Word: Fax 617-894-055l.
begin
CRC ,= 0:
SendStr1ng(S) :
OldCRC :' CRC: BSO
Wr1tel" CRC COlIPuted is ')' TASKING
WordLn( CRC):
SendByte(OldCRC) :
SendByte(H1(OldCRC)) :

CIRCLE # 28 ON READER SERVICE CARD

JANUARY 1992 EMBEDDED SYSTEMS PROGRAMMING 39


. ....".' ,m "-~",T:I'~.~~1. ~ .::i,~ I'
i\ry;!r, .

systems.
Implementing In this case, we can still get the bene-
fits of the bytewise approach, by com-

eKes Suppose that the


initial BCC were
bining the table-build and table-lookup
steps. In effect, we are building each ta-
ble entry on the fly, each time we need it.
The code for this procedure is shown in
zero, and we Listing 4 (p.37),

process byte X, DETAILS AND GOTCHAS


tion time or loaded as a constant. Then, hat pretty much wraps up the
to process theCRC, all we have todois a
couple of Xor's and a table lookup. The
processing algorithm goes as follows:
bitwise. The result
should be what
T basic concepts of CR C process-
ing. However, we still have
some minor nits to pick, which can turn
out to be major roadblocks if you're
• Compute X = D XorLoCC) we're looking for, caught unawares.
• Use X as an index into the table, fetch First of all, almost everyone who im-
T[X] since all the C bits plements the CRC algorithms follows
• Compute the new CRC as: the rules, but every once in awhile you
T[X] XorCCl> 8) will be zero. run across one that doesn't. We've al-
ways shown the shift registers shifting
It's really quite simple. We still have to important as program size. Our 5 I 2- right, and corresponding to the low-bit-
create the initial table. It turns out not byte table may be too much for such first rule. But it doesn't have to be done
to be difficult, though. Suppose that the
initial BCC were zero, and we process
the byte X. bitwise. Then, the result
should be just what we're looking for,
since all the C bits will be zero. To gen-
Figure 6
Handcheck of CRC.
erate the table, all we need to do is pro-
Input Message = 'M' = 4Dh = D1D0110b
cess the integers from zero through 255,
using the bitwise algorithm.
Reverse the bit pattern, and append 16 zeros to get the dividend:
The results are shown in Listing 2
1011 0010 0000 0000 0000 0000
(p.34). Again, the only significant dif-
ference between the CRC algorithms is
in the values used for Feedback. Now, you
might think we have gone about as far
as we can possible go with the CRC al-
gorithm, but we can still make some
improvements. Quotient (discarded) --> 1011 1001
The problem is that grotty bitwise 1 0001 0000 0010 0001 ) 1011 0010 0000 0000 0000 0000
table computation. Weend up having to 1000 1000 0001 0000 1
provide a bitwise and bytewise CRC
routine, using the first one just to create 11 1010 0001 0000 100
the lookup table. Aesthetically, that's 10 0010 0000 0100 001
not so pleasing.
Even though the bit patterns of the 1 1000 0001 0100 1010
XjS are complex, we can see a pattern, 1 0001 0000 0010 0001
and it turns out that the table entries
can be generated with just a few shifts 1001 0001 0110 1011 0
and exclusive ORs.A word of warning, 1000 1000 0001 0000 1
though-this approach makes the Make-
Table procedure algorithm-specific. The 1 1001 0111 1011 1000
bit patterns will differ depending upon 1 0001 0000 0010 0001
the polynomial used. The code shown in
Listing 3 (p.3?) is for the CCITT poly-
nomial. The others are similar, and the
rules are given in Table 2 (pA5).
Finally, in some cases (single-chip
controllers, for example), speed is not as
Figure 5
CRC standards.

. ~' 76543210 :

G(x) = x8 + J
Input
Feedback = 80 h

LRCC-16 X "
15 14 13 12 II 10 9 8 7 6 5 4 3 2 I 0 +

G(x)=xI6+ I
Input
Feedback = 8000h

Input G(X)=XI6 xI2+x5+ I


(MSB first) Feedback = l021h

G(x) = x32 + x26 + x23 + x22 + x 16 + x 12 + x II + X 10 + x8 + x7 + x5 + x4 + X + I


Feedback = CD3 8 8 3 2 Oh
Another gotcha lies in the SDLC converted 1
gorithm also has a couple of other pecu-
Implementing liarities: two null bytes are processed
after the message is sent. I suppose
/HDLC algorithm used by IBM. It is
basically the CCITT algorithm, but
it's transm
suit is not;
out to be a

CKCs Forsberg was thinking of those added


bits in the manual division process.
They are not needed, but since he uses
with a critical difference: instead of in i-
tializing the BCC to zero, in SDLC it's
initialized to FFFFh, to catch any un-
dependent
ForSDLC
wanted null bits preceeding Iimessage. One la~
them, you need to also. Since they are
(With the standard CCITT version, the thetradeol
there, the BCC will not come out to be
BCC never changes from zero until the often speCl
zero when the transmitted BCC is pro-
first non-zero bit is encountered.) gorithms t
cessed, so the two are compared. XM 0-
DEM sends the BCC high byte first. In SDLC, the resulting BCC is also up with 96
that way. The CRC will still work,
is not bad
whether the data is sent LSB first, first
proach is 1
byte first, or not. It's just that nobody
are transIT
will be able to read the message!
for interm
The most notable violator is in the
XMODEM/CRC algorithm. When
Figure 7 choice bUl
Result of processing eight data bits. and/or re,
Chuck Forsberg implemented this code,
copied inti
he found that on the 8080 it's a lot easier
to shift registers left than right. Basical- Initial value fore it's tl
ly, the XMODEM algorithm is CCITT CIS CI4 Cl3 Cl2 Cil CIQ C9 Cg C7 C6 Cs C4 C3 C2 C1 Co proach is t
done backwards. The bytes are pro- the data il
cessed in order and, of course, sent LSB the buffer
first (since LSB is controlled by hard- once the i
ware), but the CRC is done as though can run at
.............................................................................................................................. link.Simil
the bytes were being sent MSB first. Be-
X7 X6 Xs X4 X3 X2 XI Xo X7 X6 Xs X4 best to reo
cause the XMODEM code is so unique,
the ta ble-driven version of it is included X7 X6 Xs X4 X3 X2 XI Xo process it 1
in Listing 5 (p.39). The XMODEM al- X3 X2 Xl Xo X3 X2 Xl Xo X3 X2 XI Xo
WINDING

T~
knowingh
fu

tant to you
rithms we
the state 0
Just re.
ject with I
someone t
sure that
whatthea

\\,.
..... .1 ~~_
- I've seen e
comes ano
. -:-~ . --... plain wror
done diffe

Your Old Patched ..Up as is Going Down


ceiving en,
error, and
hair out tl
VENIX Industrial Strength UNIX to the Rescue lem. The 1
Good luck
• Licensed AT&TIUSL UNIX System V 3.2/4.0 VENIX is AT&T UNIX ruggedized for acquisition and
control. It's the only OS that delivers guaranteed real time,
• POSIX 1003.4 Real Time Functionality
enhanced performance and aU the UNIX development tools
• Fast, Deterministic, Fully Pteemptable Kernel for 386/486 microcomputer users.
• Embedded Disk And ROM Configurations VENIX can accelerate your product development and
• Homogeneous Development And Target Environment provide the stable, open system your market demands. Call
(617) 661-1230 for a FREE UNIX Technical Overview.
• Build On 3,000+ Off-The-Shelf Programs
,,~ Ventu,Com
W-- Industrial Strength UNIX
CIRCLE # 31 ON READER SERVICE CARD
1-----.----- ..--.------.--.-- ...---..-----------.----
..--._-.-.----------.-.---------.--.---~ ..

n the SOLC converted to its ones complement before


by IBM. It is it's transmitted. Therefore, the end re- Grappel, Robert. "Generating CRCs \\ ilh
gorithm, but sult is not a zero BCe. Instead, it turns Software," EDN, Oct. 1984, p. 205.
instead of ini- out to be a constant but non-zero value In SOLC, the BCC is Hamilton, Dennis E. "BCCITT.CL: Pen-
, in SOLC it's dependent only upon the polynomial. field, N.Y.: MSW Company, 1985.
:itch any un- For SOLC, the magic number is FOB8h. also converted to McNamara, John E. Technical Aspects of
19 a message. One last point: we've talked about Data Communications. Bedford, Mass.: Digital
Tversion, the the tradeoff between speed and size, and its ones Press, 1982, pp. 110-122.
zero until the often speed is quite important. The al- Morse, Greg. "Calculating CRCs by Bits and
Itered.) gorithms used in XMOOEM can keep complement Bytes," Byte. Sept. 1986, pp. 115-123.
~ BCC is also up with 9600-baud transmission, which Perez, Aram. "Byte-wise CRC Calcula-
is not bad at all. However, a better ap- before it's tions," IEEE Micro, June 1983, pp. 40-50.
proach is not to ask them to try. If you Peterson, W. "Cyclic Codes for Error Detec-
are transmitting bytes without facilities transmitted. tion," Proc. IRE. Jan. 1961, pp. 228-235.
for intermediate storage, you have no Ritter, Terry "The Great CRC Mystery: Dr.
choice but to process as you transmit Therefore, the end DaM's Journal. Feb. 1986, pp. 26-84.
and/or receive. But usually, the data is Tanenbaum, Andrew S. Computer /Vel-
copied into a block buffer anyway, be- result is not a zero works. Englewood Cliffs, N.J.: Prentice-Hall,
fore it's tninsmitted. So, the best ap- 1981,pp.128-133.
proach is to precalculate the BCC from BCC. Wecker, S. "A Table-Lookup Algorithm for
the data in the buffer and append it to Software Computation of Cyclic Redundancy
the buffer before you send it. That way, Check (CRC)," Digital Equipment Corporation
once the block transmission starts, it gram and has developed numerous Memorandum, 1974.
can run at the full bandwidth of the data analysis and real-time programs. Cren-
link. Similarly, on the receiving end, it's shaw holds a Ph.D. in physicsfrom Au- The author would also like to acknowledge the
best to receive and buffer the data, then burn University. Computer science he assistance on CompuServe of Tom Caurall. Phi-
process it between blocks. learned the hard way. lippe Auphelle, Irv Hoff, and Dennis Hamilton.

WINDING DOWN
hat about wraps up the story for

T CRCs. I hope you liked it. It's


fun to work with them, and
knowing how may turn out to be impor-
Table 2
Bytewlse algorithms.
tant to you someday. The bytewise algo- CCITT and SDLCjHDLC
rithms we've covered are pretty much Build Table:
the sta te of the art. z := i Xor (i Shl 4)
Just remember: approach this sub- Table[i) := (z Shl 8) Xor (z Shl 3) Xor (z Shr 4)
ject with care. If you're working with
someone to implement a CRC, make Update CRC:
sure that all parties agree precisely CRe := (CRC Shr 8) Xor Table[Data Xor Lo(CRC));
what the algorithm is. Each time I think
I've seen every possible variation, along XMODEM
comes another one--some of them just Build Table:
plain wrong. Remember, if anything is z := 1 Xor (1 Shr 4)
done differently at the sending and re- Table[i) := z Xor (z Shl 5) Xor (z Shl 12);
ceiving ends, the CRC will declare an
error, and you'll end up tearing your Update CRC:
hair out trying to figure out the prob- CRC := (CRC Shl 8) Xor Table[Data Xor H1(CRC»);
lem. The test-case strings should help.
Good luck. CRC-16
sitian and
Build Table:
real time,
ment tools if Parity(1) then
T := $C001
ment n_-i Jack Crenshaw is a consultant based in else
ands. Tampa. Fla. He wrote his first com- T := 0;
)verview.
puter program in 1954. and has been Table[i] := T Xor (i Shl 6) Xor (i Shl 7);
involved with software design, develop-
ment, and methodologies ever since. He Update CRC:
did much early work in the space pro- CRC := (CRC Shr 8) Xor Table[Data Xor Lo(CRC));

You might also like