unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg = 0;
unsigned short current;
for (i = 0; i < len; i)
{
current = message[i] << 8;
for (j = 0; j < 8; j)
{
if ((short)(crc_reg ^ current) < 0)
crc_reg = (crc_reg << 1) ^ 0x1021;
else
crc_reg <<= 1;
current <<= 1;
}
}
return crc_reg;
}
以上的讨论中,消息的每个字节都是先传输MSB,CRC16-CCITT标准却是按照先传输LSB,消息右移进寄存器来计算的。只需将代码改成判断寄存器的LSB,将0x1021按位颠倒后(0x8408)与寄存器异或即可,如下所示:
unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg = 0;
unsigned short current;
for (i = 0; i < len; i)
{
current = message[i];
for (j = 0; j < 8; j)
{
if ((crc_reg ^ current) & 0x0001)
crc_reg = (crc_reg >> 1) ^ 0x8408;
else
crc_reg >>= 1;
current >>= 1;
}
}
return crc_reg;
}
该算法使用了两层循环,对消息逐位进行处理,这样效率是很低的。为了提高时间效率,通常的思想是以空间换时间。考虑到内循环只与当前的消息字节和crc_reg的低字节有关,对该算法做以下等效转换:
unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg = 0;
unsigned char index;
unsigned short to_xor;
for (i = 0; i < len; i)
{
index = (crc_reg ^ message[i]) & 0xff;
to_xor = index;
for (j = 0; j < 8; j)
{
if (to_xor & 0x0001)
to_xor = (to_xor >> 1) ^ 0x8408;
else
to_xor >>= 1;
}
crc_reg = (crc_reg >> 8) ^ to_xor;
}
return crc_reg;
}
现在内循环只与index相关了,可以事先以数组形式生成一个表crc16_ccitt_table,使得to_xor = crc16_ccitt_table[index],于是可以简化为:
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-38614-3.html
最终还是人在操作
美日口粮做事的啦