最近在对接一个车载定位,对方提供的文档中CRC的算法使用的是C语言的代码,我完全没有研究过C语言,现在需要将C语言转换为C#
U16 GetCrc16(const U8* pData, int nLength)
{
U16 fcs = 0xffff; // 初始化
while(nLength>0){ fcs = (fcs >> 8) ^ crctab16[(fcs ^ *pData) & 0xff];
nLength--;
pData++;
}
return ~fcs; // 取反
}
static UInt32[] CRC32=new UInt32[256];
static bool init = false;
//初始化表
static void init_table()
{
UInt32 i, j;
UInt32 crc;
for (i = 0; i < 256; i++)
{
crc = i;
for (j = 0; j < 8; j++)
{
if ((crc & 1)==1)
{
crc = (crc >> 1) ^ 0xEDB88320;
}
else
{
crc = crc >> 1;
}
}
CRC32[i] = crc;
}
}
//crc32实现函数
UInt32 crc32(ref byte[] buf, Int32 len)
{
UInt32 ret = 0xFFFFFFFF;
Int32 i;
if (!init)
{
init_table();
init = true;
}
for (i = 0; i < len; i++)
{
if(i<buf.Count())
ret = CRC32[((ret & 0xFF) ^ buf[i])] ^ (ret >> 8);
else
ret = CRC32[((ret & 0xFF) ^ 0xff)] ^ (ret >> 8);//在后面补0xff
}
ret = ~ret;
return ret;
}
网上很多的,你要注意位数,有CRC16,CRC32