#include <stdio.h>
typedef unsigned short ushort;
typedef unsigned char uchar;
typedef union _CRC
{
ushort crc16;
uchar by[2];
} CRC;
//输入不带CRC码的数据时,返回值是CRC码
//输入带CRC码的数据时,则可以进行校验,返回0时CRC校验成功,否则CRC校验失败
ushort CRC16(uchar *ba, int size)
{
CRC crc;
crc.crc16 = 0xffff;
int i, l;
for (i=0; i<size; i++)
{
uchar ch = ba[i];
crc.by[0] = crc.by[0] ^ ch;
for (l=0; l<8; l++)
{
if (crc.by[0] & 0x01)
{
crc.crc16 = crc.crc16 >> 1;
crc.crc16 = crc.crc16 ^ 0xa001;
}
else
{
crc.crc16 = crc.crc16 >> 1;
}
}
}
uchar swap = crc.by[0];
crc.by[0] = crc.by[1];
crc.by[1] = swap;
return crc.crc16;
}
void main()
{
printf("0x%x",'9');
uchar ba[9] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,0x39};
CRC crc;
//计算CRC码
crc.crc16 = CRC16(ba, 9);
printf("高字节:0x%x, 低字节:0x%x\n", crc.by[1], crc.by[0]);
//CRC校验
uchar bb[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0xb0, 0xcf};
if (0 == CRC16(bb, 10))
{
printf("bb 校验成功!");
}
else
{
printf("bb 校验失败!");
}
}