想写一个程序得到16位CRC校验值,利用的多项式是CRC-16/CCITT FALSE “x^16+x^12+X^5+1”,
但是输入的结果只有高8位,有人知道是为什么吗?
static void Main(string[] args)
{
byte[] bt1 = new byte[] { 0x20, 0x84, 0x18,0x12, 0x00, 0x10, 0x08, 0xC0, 0x00, 0x00,0x05, 0x00, 0x00, 0x1E, 0x08, 0x1E, 0x08};
byte[] result = Crc16(bt1, 0, 0);
Console.WriteLine(Convert.ToString(result[0], 16).PadLeft(4, '0').ToUpper());// 将字节数组转换成16进制字符串,PadLeft 检查位数够不够,不够在左侧补0,ToUpper 转换为大写字符
Console.ReadLine();
}
public static byte[] Crc16(byte[] buffer, int start = 0, int len = 0)
{
if (buffer == null || buffer.Length == 0) return null;
if (start < 0) return null;
if (len == 0) len = buffer.Length-start;
int length = start + len;
if (length > buffer.Length) return null;
ushort crc = 0xFFFF;// Initial value
for (int i = start; i < length; i++)
{
crc ^= (ushort)(buffer[i] << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) > 0)
crc = (ushort)((crc << 1) ^ 0x1021);
else
crc = (ushort)(crc << 1);
}
}
byte[] ret = BitConverter.GetBytes(crc);
Array.Reverse(ret);
return ret;
}
```
crc16的算法网上有现成的代码,目测你这算法不对把,j循环里应该每次右移一位,你为什么是左移
CCITT 和标准的CRC16除了多项式一个是1021,一个是A001,其他完全一样
所以你找个标准的代码把多项式改了就行