Monday, January 18, 2010

CRC CCITT

After failing to find the answer to VFP's SYS(2007) return value for CRC, I did a little more hunting and found there are other algorithms that produce different results. I ended up finding another page from www.sanity-free.org that actually did the trick (http://www.sanity-free.org/133/crc_16_ccitt_in_csharp.html). Using a CRC-16, CCITT Algorithm and passing 0xFFFF as an initial value, it produced the same return value as VFP.

A listing of the code is below:

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 <>
{
crc = (ushort)((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 <>
{
temp = 0;
a = (ushort)(i <<>
for (int j = 0; j <>
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort)((temp <<>
}
else
{
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
}
}

Here is the code I wrote to produce the result:


System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
byte[] byteKey = encoding.GetBytes(strKey);
Crc16Ccitt crcChecksum = new Crc16Ccitt(InitialCrcValue.NonZero1);
intCheckSumReturn = crcChecksum.ComputeChecksum(byteKey);



No comments:

Post a Comment