使用内部硬件实现无初始值的CRC校验

This commit is contained in:
nnhy 2014-10-10 06:56:29 +00:00
parent f13e600b96
commit ba6500e60d
2 changed files with 37 additions and 5 deletions

37
Sys.cpp
View File

@ -421,23 +421,54 @@ static const uint c_CRCTable[ 256 ] =
0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4
};
uint TSys::Crc(const byte* buf, uint len, uint crc)
uint TSys::Crc(const void* buf, uint len, uint crc)
{
byte* ptr = (byte*)buf;
while(len-- > 0)
{
crc = c_CRCTable[ ((crc >> 24) ^ (*buf++)) & 0xFF ] ^ (crc << 8);
crc = c_CRCTable[ ((crc >> 24) ^ (*ptr++)) & 0xFF ] ^ (crc << 8);
}
return crc;
}
// 硬件实现的Crc
uint TSys::Crc(const void* buf, uint len)
{
#ifdef STM32F4
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_CRC, ENABLE);
#else
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE);
#endif
CRC_ResetDR();
// STM32的初值是0xFFFFFFFF而软Crc初值是0
//CRC->DR = __REV(crc ^ 0xFFFFFFFF);
//CRC->DR = 0xFFFFFFFF;
uint* ptr = (uint*)buf;
len >>= 2;
while(len-- > 0)
{
CRC->DR =__REV(*ptr++); // 字节顺序倒过来,注意不是位序,不是用__RBIT指令
}
uint crc = CRC->DR;
#ifdef STM32F4
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_CRC, DISABLE);
#else
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, DISABLE);
#endif
return crc;
}
static const ushort c_CRC16Table[] =
{
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400,
};
ushort TSys::Crc16(const byte* buf, uint len, ushort crc)
ushort TSys::Crc16(const void* buf, uint len, ushort crc)
{
if (!buf || !len) return 0;

5
Sys.h
View File

@ -96,8 +96,9 @@ public:
Func OnStop;
// CRC32校验
uint Crc(const byte* buf, uint len, uint crc = 0);
ushort Crc16(const byte* buf, uint len, ushort crc = 0xFFFF);
uint Crc(const void* buf, uint len);
uint Crc(const void* buf, uint len, uint crc);
ushort Crc16(const void* buf, uint len, ushort crc = 0xFFFF);
void ShowHex(byte* buf, uint len, char sep = '\0');// 显示十六进制数据,指定分隔字符
void ShowString(byte* buf, uint len = 0, bool autoEnd = true); // 显示字符串,不指定长度时自动找\0