Click here to Skip to main content
Click here to Skip to main content

C# CCITT-8 CRC Algorithm

, 5 Feb 2010 GPL3
Rate this:
Please Sign up or sign in to vote.
An article on a C# Cyclic Redundancy Check (CRC) algorithm

Introduction

Chances are that if you've arrived at this page, you are communicating with some sort of god-awful, backdated manufacturing/embedded device that requires you to build messages one byte at a time into a frame or some other type of logical package with a CCITT-8 CRC checksum at the end. In any event, I won't bother going into CRCs, checksums and the like here. If you want to read about them, there are plenty of articles on the subject out there.

Background

I couldn't find a C# CCITT-8 CRC algorithm anywhere. So, when I finally got this done, I figured I'd post it in the hopes of helping someone avoid the fruitless search I had undertaken. I also got some great feedback from some random developers and have put some of their helpful comments to use in this updated version of the code. Hope it helps you out.

Using the Code

Here is the example class; it is very simple. You'll probably want to just cut and paste it into your project where appropriate. To use it, pass in a byte array that contains the data you need a checksum for. It will spit the 8bit checksum back out as a single byte. You basically create a new class instance passing in the polynomial you want to use to calculate the checksum with. I have included only 8 bit polynomials here because I think everything else is pretty well represented elsewhere on the net. You can recalculate the table for a single class instance by calling the GenerateTable function and using the property setter to set the table.

///
/// This enum is used to indicate what kind of checksum you will be calculating.
/// 
public enum CRC8_POLY
{
	CRC8 = 0xd5,
	CRC8_CCITT = 0x07,
	CRC8_DALLAS_MAXIM = 0x31,
	CRC8_SAE_J1850 = 0x1D,
	CRC_8_WCDMA = 0x9b,
};

/// 
/// Class for calculating CRC8 checksums...
/// 
public class CRC8Calc {
    private byte[] table = new byte[256];
	
    public byte Checksum(params byte[] val ) 
	{
		if(val == null) 
			throw new ArgumentNullException("val");
			
        byte c = 0;

        foreach ( byte b in val ) 
		{
            c = table[c ^ b];
        }
    
        return c;
    } 

	public byte[] Table
	{
		get
		{
			return this.table;
		}
		set
		{
			this.table = value;
		}
	}
	
	public byte[] GenerateTable(CRC8_POLY polynomial)
	{
		byte[] csTable = new byte[256];
		
		for ( int i = 0; i < 256; ++i ) 
		{
            int curr = i;
			
            for ( int j = 0; j < 8; ++j ) 
			{
                if ((curr & 0x80) != 0) 
				{
                    curr = (curr << 1) ^ (int)polynomial;
                } 
				else 
				{
                    curr <<= 1;
                }
            }
			
            csTable[i] = (byte)curr;
        }
		
		return csTable;
	}
	
    public CRC8Calc(CRC8_POLY polynomial) 
	{
		this.table = this.GenerateTable(polynomial);
    }
}

Example

using System;

public class CRC8Test
{
	public static void RunSnippet()
	{
		byte checksum;
		byte[] testVal = new byte[]
		{0xee, 0x01, 0x13, 0x00, 0x06, 0x1c, 0x00, 0x20,  0x1d, 0x00, 0x00};
		CRC8Calc crc_dallas = new CRC8Calc(CRC8_POLY.CRC8_DALLAS_MAXIM);
		checksum = crc_dallas.Checksum(testVal);
		WL(checksum);
		CRC8Calc crc = new CRC8Calc(CRC8_POLY.CRC8_CCITT);
		checksum = crc.Checksum(testVal);
		WL(checksum);
	}
	
	#region Helper methods
	
	public static void Main()
	{
		try
		{
			RunSnippet();
		}
		catch (Exception e)
		{
			string error = string.Format
			("---\nThe following error occurred while executing 
				the snippet:\n{0}\n---", e.ToString());
			Console.WriteLine(error);
		}
		finally
		{
			Console.Write("Press any key to continue...");
			Console.ReadKey();
		}
	}

	private static void WL(object text, params object[] args)
	{
		Console.WriteLine(text.ToString(), args);	
	}
	
	#endregion
}

History

  • 5th June, 2007 -- Original version posted
  • 5th February, 2010 -- Article updated

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Rob Magee
Other Apostrophe Systems
United States United States
Rob Magee is a software engineer for Apostrophe Systems specializing in RFID, SAP Auto-Id Infrastructure Integration, Security, C#, Java, ABAP, Python, Supply-Chain and Manufacturing systems, etc.

Comments and Discussions

 
QuestionNote for VB.NET-ers PinmemberSimon Dixey22-Nov-12 22:27 
QuestionVerified code, and a comment PinmemberSeattleC++11-Sep-12 19:13 
QuestionCan you code a dynamic hash function? PinmemberTushar Arora20-Aug-10 7:59 
QuestionCRC8-CCITT??? PinmemberMad as a Hatter4-Feb-10 16:45 
AnswerRe: CRC8-CCITT??? PinmemberRob Magee5-Feb-10 12:06 
GeneralRe: CRC8-CCITT??? PinmemberMad as a Hatter6-Feb-10 5:03 
GeneralRe: CRC8-CCITT??? PinmemberRob Magee6-Feb-10 8:32 
Thanks again. And your website IS cool.
QuestionHow to calculate CRCTable? PinmemberGeorgi Petrov29-Nov-09 9:41 
AnswerRe: How to calculate CRCTable? [modified] PinmemberMad as a Hatter4-Feb-10 16:51 
QuestionHow the CRC table calculated from ? Pinmemberwhfongs25-Aug-07 15:56 
GeneralOptimizations PinmemberRi Qen-Sin5-Jun-07 12:15 
GeneralRe: Optimizations PinmemberRob Magee6-Jun-07 3:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 6 Feb 2010
Article Copyright 2007 by Rob Magee
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid