kazenomelodi 2017-03-10 14:38 采纳率: 0%
浏览 874

CRC算法问题,请高手们帮我看看吧!!!!谢谢了!

http://blog.chinaunix.net/uid-20416869-id-173134.html 随便找的博客地址,别人的

unsigned short do_crc(unsigned char *message, unsigned int len)
{
int i, j;
unsigned short crc_reg;

crc_reg = (message[0] << 8) + message[1];
for (i = 0; i < len; i++) 
{
    if (i < len - 2)
        for (j = 0; j <= 7; j++) 
        { 
            if ((short)crc_reg < 0)
                crc_reg = ((crc_reg << 1) + (message[i + 2] >> (7 - i))) ^ 0x1021;
            else 
                crc_reg = (crc_reg << 1) + (message[i + 2] >> (7 - i));      
        }
     else
        for (j = 0; j <= 7; j++) 
        { 
            if ((short)crc_reg < 0)
                crc_reg = (crc_reg << 1) ^ 0x1021;
            else 
                crc_reg <<= 1;             
        }         
}
return crc_reg;

}

显然,每次内循环的行为取决于寄存器首位。由于异或运算满足交换率和结合律,以及与0异或无影响,消息可以不移入寄存器,而在每次内循环的时候,寄存器首位再与对应的消息位异或。改进的代码如下:
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;

}

上面那个程序搞懂了,下面那个看不懂啊,怎么变成那样的!?帮我看看吧谢谢了!

  • 写回答

1条回答 默认 最新

  • devmiao 2017-03-10 15:32
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题