How to calculate CRC in C#?

First of all, I want to beg your pardon about the frequency of posts last time. I'm completely understaffed and have a ton of things to do for my job. This is why, today I'll just write a quick post about checksum calculation in C#. It might be very useful for any of you working with devices or external systems.

CRC – Cyclic Redundancy Check is an algorithm which is widely used in different communication protocols, packing and packaging algorithms for assuring robustness of data. The idea behind it is simple – calculate a unique checksum (frame check sequence) for each data frame, based on its content and stick it at the end of each meaningful message. Once data is received, it’s possible to perform the same calculation and compare results – if results are similar, message is ok.

There are two kinds of CRC – 16 and 32 bit. There are also less used checksums for 8 and 64 bits. All this is about appending a string of zeros to the frame equal in number of frames and modulo two device by using generator polynomial containing one or more bits, then checksum to be generated. This is very similar to performing a bit-wise XOR operation in the frame, while the remainder is actually our CRC.

In many industries, the first polynomial is in use to create CRC tables and then apply it for performance purposes. The default polynomial, defined by IEEE 802.3 is 0xA001 for 16 bit and 0×04C11DB7 for 32 bit. We're in C#, thus we should use its inversed version which is 0×8408 for 16 bit and 0xEDB88320 for 32 bit. We're going to use those polynomials also in our sample.

So let’s start. Because CRC is HashAlgorithm after all, we can derive our classes from System.Security.Cryptography.HashAlgorithm class.

Then, upon first creation we'll generate hashtables with CRC values to enhance future performance. It’s all about values table for bytes from 0 to 255 , so we should calculate it only once and then we can use it statically.

Share

About the Author

Hello! My name is Tamir Khason, and I am software architect, project manager, system analyst and [of course] programmer. In addition to writing big amount of documentation, I also write code, a lot of code. I used to work as a freelance architect, project manager, trainer, and consultant here, in Israel, but recently join the company with extremely persuasive idea - to make a world better place. I have very pretty wife and 3 charming kids, but unfortunately almost no time for them.

I have done some research with the CRC, and i dont think the crc in my specific problem (AMBrc)is compliant to the CRC16-CCITT standard.

I downloaded the crc code to carlculate CRC16-CCITT and CRC32-CCITT but none of them works for calculating the AMBrc messages. I'm convinced it is a 16-bit CRC algorithm but dont know wich, there is so many different algorithms.