Thursday, July 24, 2008

c# CRC16 ccitt

While working with serial port, I was required to perform crc checking on data that I received.
I used the following code.



using System;
using System.Collections.Generic;
using System.Text;

namespace SerialPortTerminal
{
public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F }

public class Crc16Ccitt
{
const ushort poly = 4129;
ushort[] table = new ushort[256];
ushort initialValue = 0;

public ushort ComputeChecksum(byte[] bytes)
{
ushort crc = this.initialValue;
for (int i = 0; i < bytes.Length; i++)
{
crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}

public byte[] ComputeChecksumBytes(byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return new byte[] { (byte)(crc >> 8), (byte)(crc & 0x00ff) };
}

public Crc16Ccitt(InitialCrcValue initialValue)
{
this.initialValue = (ushort)initialValue;
ushort temp, a;
for (int i = 0; i < table.Length; i++)
{
temp = 0;
a = (ushort)(i << 8);
for (int j = 0; j < 8; j++)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort)((temp << 1) ^ poly);
}
else
{
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
}
}





6 comments:

Anonymous said...

The code is works. Thank you very much!

Anonymous said...

If you copy code from the internet you should give credit to the original author ...

Anonymous said...

Looks a lot like this

http://www.sanity-free.com/133/crc_16_ccitt_in_csharp.html

for ict 99 said...

Great Article

Dot Net Training Institutes in Chennai | .net training online | Dot Net Training in Chennai | .Net Training in Chennai | ASP.NET Training



C# Training | ASP.NET Training | ASP.NET MVC Training in Chennai

Dot Net Interview Questions

navya said...

Great Article
C# Training in Chennai | C# Online Training | ASP.NET Training in Chennai

C# Training in Chennai | Dot Net Training in Chennai | Dot Net Training in Chennai

Syed Haider said...

Would you guys help me do this stuff , i have this string
"$0290,604,0,00,39,40,41,42,43,1,2,3,1,2,05186CrLf"

In this string checksum is 05186 would you please tell how to calculate the checksum using this data original data is "$0290,604,0,00,39,40,41,42,43,1,2,3,1,2"