日期:2014-05-16 浏览次数:21073 次
unsigned short CalcCrc16(unsigned char * pData, int nLength)
{
unsigned short cRc_16 = 0x0000; // 初始化
const unsigned short cnCRC_16 = 0x8005;
unsigned long cRctable_16[256];
unsigned short i,j,k;
for (i=0,k=0;i<256;i++,k++)
{
cRc_16 = i<<8;
for (j=8;j>0;j--)
{
if (cRc_16&0x8000) //反转时cRc_16&0x0001
cRc_16 = (cRc_16<<=1)^cnCRC_16; //反转时cRc_16=(cRc_16>>=1)^gEnpoly
else
cRc_16<<=1; //反转时cRc_16>>=1
}
cRctable_16[k] = cRc_16;
}
while (nLength>0)
{
cRc_16 = (cRc_16 << 8) ^ cRctable_16[((cRc_16>>8) ^ *pData) & 0xff];
nLength--;
pData++;
}
return cRc_16;
#region CRC16校验
/// <summary>
///CRC16校验算法,(低字节在前,高字节在后)
/// </summary>
/// <param name="data">要校验的数组</param>
/// <returns>返回校验结果,低字节在前,高字节在后</returns>
public static byte[] crc16(byte[] data)
{
if (data.Length == 0)
throw new Exception("调用CRC16校验算法,(低字节在前,高字节在后)时发生异常,异常信息:被校验的数组长度为0。");
byte[] temdata = new byte[data.Length + 2];
int xda, xdapoly;
byte i, j, xdabit;
xda = 0xFFFF;
xdapoly = 0xA001;
for (i = 0; i < data.Length; i++)
{