C语言CRC校验代码转C# 谢谢!
最近在做一个com口的开发,协议居然是用CRC16校验,不知怎么做,找了个c的,麻烦个位帮忙给转下c# 呗,感激不尽!
#define PRESET_VALUE 0xFFFF
#define POLYNOMIAL 0x8408
unsigned int uiCrc16Cal(unsigned char const * pucY, unsigned char ucX)
{
unsigned char ucI,ucJ;
unsigned short int uiCrcValue = PRESET_VALUE;
for(ucI = 0; ucI < ucX; ucI++)
{
uiCrcValue = uiCrcValue ^ *(pucY + ucI);
for(ucJ = 0; ucJ < 8; ucJ++)
{
if(uiCrcValue & 0x0001)
{
uiCrcValue = (uiCrcValue >> 1) ^ POLYNOMIAL;
}
else
{
uiCrcValue = (uiCrcValue >> 1);
}
}
}
return uiCrcValue;
}
pucY是要计算CRC16的字符数组的入口,ucX是字符数组中字符个数。
上位机收到数据的时候,只要把收到的数据按以上算法进行计算CRC16,结果为0x0000表明数据正确。
------解决方案--------------------http://blog.sina.com.cn/s/blog_589d32f50100083g.html
现成的
------解决方案--------------------
C# code
const uint PRESET_VALUE = 0xFFFF;
const uint POLYNOMIAL = 0x8408;
uint uiCrc16Cal(char[] pucY, int ucX)
{
uint ucI, ucJ;
uint uiCrcValue = PRESET_VALUE;
for (ucI = 0; ucI < ucX; ucI++)
{
uiCrcValue = uiCrcValue ^ pucY[ucI];
for (ucJ = 0; ucJ < 8; ucJ++)
{
if ((uiCrcValue & 0x0001) != 0)
{
uiCrcValue = (uiCrcValue >> 1) ^ POLYNOMIAL;
}
else
{
uiCrcValue = (uiCrcValue >> 1);
}
}
}
return uiCrcValue;
}