最新新遇到设备采用CRC-CCITT 标准CRC16(1021),网上很多相关文章,但是大都结果不对。以下代码来自https://bbs.csdn.net/topics/390876846回答中的代码
代码如下:
public static String getCRC16_CCITT(String Source)
{
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
String tmp = "";
byte[] bytes = new byte[Source.Length / 2];
for (int i = 0; i < Source.Length - 1; i++)
{
if (i % 2 == 0)
{
tmp = Source.Substring(i, 2);
bytes[i / 2] = (byte)Int16.Parse(tmp, System.Globalization.NumberStyles.HexNumber);
}
}
foreach (byte b in bytes)
{
for (int i = 0; i < 8; i++)
{
bool bit = ((b >> (7 - i) & 1) == 1);
bool c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) crc ^= polynomial;
}
}
crc &= 0xffff;
string strDest = crc.ToString("X");
return strDest;
}
测试:
02383638343734303435383131393731301909062046375D1104400000
得出结果为:F5E3
另附CRC在线校验地址:https://www.lammertbies.nl/comm/info/crc-calculation.html