CRC-8校验算法

View Code
publicenum CRC8_POLY
{
CRC8
=0xd5,
CRC8_CCIIT
=0x07,
CRC8_DALLAS_MAXIM
=0x31,
CRC8_SAE_J1850
=0x1d,
CRC_8_WCDMA
=0x9b,

};
publicclass CRC8Calc
{
privatebyte[] table =newbyte[256];
publicbyte Checksum(paramsbyte[] val)
{
if (val ==null)
thrownew ArgumentNullException("Val");
byte c =0;
foreach (byte b in val)
c
= table[c ^ b];
return c;
}
publicbyte[] Table
{
get
{
returnthis.table;
}
set
{
table
= value;
}

}

publicbyte[] GenerateTable(CRC8_POLY polynomial)
{
byte[] csTable =newbyte[256];
for (int i =0; i <256; ++i)
{
int curr = i;
for (int j =0; j <8; ++j)
{
if ((curr &0x80) !=0)
curr
= (curr <<1) ^ (int)polynomial;
else
curr
<<=1;
}
csTable[i]
= (byte)curr;
}
return csTable;
}

public CRC8Calc(CRC8_POLY polynomial)
{
this.table =this.GenerateTable(polynomial);
}

}

class Program
{
staticvoid Main(string[] args)
{

RunSnippet();

}


publicstaticvoid RunSnippet()
{
byte checksum;
byte[] testVal =newbyte[] { 0x01};
CRC8Calc crc
=new CRC8Calc(CRC8_POLY.CRC8_DALLAS_MAXIM);
checksum
= crc.Checksum(testVal);
WL(checksum);
Console.ReadKey();

}

publicstaticvoid WL(object text, paramsobject[] args)
{
Console.WriteLine(text.ToString(), args);
}
}
staticbyte CheckValue(byte[] b, int len)
{
byte crc =0;
byte j =0;
while (len --!=0)
{
for (byte i =0x80; i !=0; i >>=1)
{

if ((crc & MSB_MASK_8) !=0) // 1 0 0 0 0 0 0 0 判断crc中得最高位是否为1
{ // 如果crc中得最高位为1,就执行以下语句,与R_8做XOR运算
crc <<=1; //
crc &= LIMIT_MASK_8; // 1 1 1 1 1 1 1 1
crc ^= R_8;
}
else
crc
<<=1;
if ((b[j] & i) !=0) // 每循环一次,从数据的最高位依次取到最低位,如果取得的数据位为1,就执行以下语句
crc ^= R_8; // 1 0 0 1 1 0 1 1


}
j
++;
}
return crc;

 

你可能感兴趣的:(CRC)