i'm trying to implement Crc16 in C#. I already tried many different implementations, but most of them gives me different values. Here are some of the codes that i already used.
private static int POLYNOMIAL = 0x8408;
private static int PRESET_VALUE = 0xFFFF;
public static int crc16(byte[] data)
{
int current_crc_value = PRESET_VALUE;
for (int i = 0; i < data.Length; i++)
{
current_crc_value ^= data[i] & 0xFF;
for (int j = 0; j < 8; j++)
{
if ((current_crc_value & 1) != 0)
{
current_crc_value = (current_crc_value >> 1) ^ POLYNOMIAL;
}
else
{
current_crc_value = current_crc_value >> 1;
}
}
}
current_crc_value = ~current_crc_value;
return current_crc_value & 0xFFFF;
}
this is the another implementation that i used but both gives different values
const ushort polynomial = 0xA001;
ushort[] table = new ushort[256];
public ushort ComputeChecksum(byte[] bytes)
{
ushort crc = 0;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)(crc ^ bytes[i]);
crc = (ushort)((crc >> 8) ^ table[index]);
}
return crc;
}
public byte[] ComputeChecksumBytes(byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return BitConverter.GetBytes(crc);
}
public Crc16()
{
ushort value;
ushort temp;
for (ushort i = 0; i < table.Length; ++i)
{
value = 0;
temp = i;
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x0001) != 0)
{
value = (ushort)((value >> 1) ^ polynomial);
}
else
{
value >>= 1;
}
temp >>= 1;
}
table[i] = value;
}
}
The value I`m using is an Octet String "[jp3]TEST [fl]Flashing[/fl]" and its expected value is 95F9 in hex. This is an example on the guide of NTCIP protocol
Thanks
This:
will work for the only test given here http://www.ite.org/standards/1203v03-04%20Part%201%20dms2011.pdf (around page 158,
CRC = 0x52ED
).For the string example of the PDF, as written some pages later:
(emphasis added)
so:
This shows that the protocol is little endian (as my PC, that is an Intel). In fact the CRC-16 of the string is 0xF995, but these 16 bits in memory appear as 0x95 0xF9 (as in the example, that shows the single bytes).