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

來源:互聯網
上載者:User

來源:http://blog.csdn.net/kuzhuxuan/archive/2006/05/30/763300.aspx

 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;
  }
 }
}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.