?? crc.c
字號:
// CCITT: x^16 + x^12 + x^5 + x^0 (0x1021)
// CRC-16: x^16 + x^15 + x^2 + x^0 (0x8005)
#define CRC_16_POLYNOMIALS 0x8005
// ---------------------------------------------------------
// 方法2:按位直接映射
// 優點:直觀,高效
// 缺點:
// ---------------------------------------------------------
uchar ByteInvert(uchar chSrc )
{
uchar chDst=0;
if ( chSrc & 0x80 ) chDst |= 0x01;
if ( chSrc & 0x40 ) chDst |= 0x02;
if ( chSrc & 0x20 ) chDst |= 0x04;
if ( chSrc & 0x10 ) chDst |= 0x08;
if ( chSrc & 0x08 ) chDst |= 0x10;
if ( chSrc & 0x04 ) chDst |= 0x20;
if ( chSrc & 0x02 ) chDst |= 0x40;
if ( chSrc & 0x01 ) chDst |= 0x80;
return(chDst);
}
uint WordInvert(uint chSrc )
{
uint chDst=0;
if ( chSrc & 0x8000 ) chDst |= 0x0001;
if ( chSrc & 0x4000 ) chDst |= 0x0002;
if ( chSrc & 0x2000 ) chDst |= 0x0004;
if ( chSrc & 0x1000 ) chDst |= 0x0008;
if ( chSrc & 0x0800 ) chDst |= 0x0010;
if ( chSrc & 0x0400 ) chDst |= 0x0020;
if ( chSrc & 0x0200 ) chDst |= 0x0040;
if ( chSrc & 0x0100 ) chDst |= 0x0080;
if ( chSrc & 0x0080 ) chDst |= 0x0100;
if ( chSrc & 0x0040 ) chDst |= 0x0200;
if ( chSrc & 0x0020 ) chDst |= 0x0400;
if ( chSrc & 0x0010 ) chDst |= 0x0800;
if ( chSrc & 0x0008 ) chDst |= 0x1000;
if ( chSrc & 0x0004 ) chDst |= 0x2000;
if ( chSrc & 0x0002 ) chDst |= 0x4000;
if ( chSrc & 0x0001 ) chDst |= 0x8000;
return(chDst);
}
uint CalStrCRC16(uchar* pchMsg, uchar wDataLen)
{
uchar i, chChar;
uint wCRC = 0x0000;
while (wDataLen--)
{
chChar = *pchMsg++;
chChar = ByteInvert(chChar);
wCRC ^= (((uint) chChar) << 8);
for (i = 0; i < 8; i++)
{
if (wCRC & 0x8000)
wCRC = (wCRC << 1) ^ CRC_16_POLYNOMIALS;
else
wCRC <<= 1;
}
}
wCRC = WordInvert(wCRC);
wCRC^=0xFFFF;
return wCRC;
}
bit ChkCRC16(uchar *String,uchar length)
{
uint temp,temp_temp;
temp=CalStrCRC16(String,length-2);
temp_temp=(String[length-1]<<8)+String[length-2];
if(temp!=temp_temp) return FALSE;
return TRUE;
}
uchar CalCRC8(uchar x, uchar temp) //Calculate 8 bits CRC code of a data
{uchar i, y;
for(i=0; i<8; i++)
{
y = x^temp;
if(y &= 0x01) temp ^= 0x18;
temp >>= 1;
if(y) temp |= 0x80;
x >>= 1;
}
return(temp);
}
bit ChkCRC8(uchar *String, uchar length) //length為總長,String尾部為待校驗CRC8
{
uchar temp = 0;
for(k=0; k<(length-1); k++)
temp = CalCRC8(String[k], temp);
if(temp != String[length - 1]) return(FALSE);
return(TRUE);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -