# C#串口通訊CRC校正碼計算類

using System;

namespace BQ.Terminal.Gateway
{
/// <summary>
/// 訊息CRC校正演算法
/// </summary>
public class CRC
{
//private int key = 0x11021H;
public CRC()
{

}
public static int GetKey(byte[] data)
{
int count = data.Length;
byte[] buf = new byte[data.Length+2];
data.CopyTo(buf,0);
int ptr = 0;
int i = 0;
int crc = 0;
byte crc1,crc2,crc3;
crc1 = buf[ptr++];
crc2 = buf[ptr++];
buf[count] = 0;
buf[count+1] = 0;
while(--count >= 0)
{
crc3 = buf[ptr++];
for(i =0;i<8;i++)
{
if(((crc1&0x80)>>7) == 1)//判斷crc1高位是否為1
{
crc1 = (byte)(crc1 << 1); //移出高位
if(((crc2&0x80)>>7) == 1)//判斷crc2高位是否為1
{
crc1 = (byte)(crc1 | 0x01);//crc1低位由0變1
}
crc2 = (byte)(crc2 << 1);//crc2移出高位
if(((crc3&0x80)>>7) == 1) //判斷crc3高位是否為1
{
crc2 = (byte)(crc2 | 0x01); //crc2低位由0變1
}
crc3 = (byte)(crc3 << 1);//crc3移出高位
crc1 = (byte)(crc1 ^ 0x10);
crc2 = (byte)(crc2 ^ 0x21);
}
else
{
crc1 = (byte)(crc1 << 1); //移出高位
if(((crc2&0x80)>>7) == 1)//判斷crc2高位是否為1
{
crc1 = (byte)(crc1 | 0x01);//crc1低位由0變1
}
crc2 = (byte)(crc2 << 1);//crc2移出高位
if(((crc3&0x80)>>7) == 1) //判斷crc3高位是否為1
{
crc2 = (byte)(crc2 | 0x01); //crc2低位由0變1
}
crc3 = (byte)(crc3 << 1);//crc3移出高位
}
}
}
crc = (int)((crc1<<8) + crc2);
return crc;
}
}
}

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD