C# CRC校正的一點感悟

來源:互聯網
上載者:User

標籤:

今天在鼓搗一個手持操作器的時候,遇到一點問題,記錄一下今天的經驗包

由於之前公司產品在校正時基本上都是和校正,今天在準備用C#類比一個古董操作器的時候,卻遇到一個問題,模擬器發出的資料,主板一律不回複,對比通訊協議也沒發現什麼問題。由於文檔有些不全,只是知道通訊格式,對比之後覺得應該是校正出了問題。由於CRC校正是資料通訊領域最常用的校正方式,問了幾個老傢伙之後才知道這個四位元組ASCII碼校正和應該是CRC16-CCITT產生的,然後就去仔細看大學時候煞筆了很久也沒明白的CRC校正的細節。

具體CRC如何產生我不闡述了,關鍵點在於“產生多項式”和初始值。

CRC16-CCITT的產生多項式是 0x1021;

不多說了,提供代碼CRC16-CCITT類

public class Crc16Ccitt    {        public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F }        const ushort poly = 4129;        ushort[] table = new ushort[256];        ushort initialValue = 0;        public Crc16Ccitt(InitialCrcValue initialValue)        {            this.initialValue = (ushort)initialValue;            ushort temp, a;            for (int i = 0; i < table.Length; ++i)            {                temp = 0;                a = (ushort)(i << 8);                for (int j = 0; j < 8; ++j)                {                    if (((temp ^ a) & 0x8000) != 0)                    {                        temp = (ushort)((temp << 1) ^ poly);                    }                    else                    {                        temp <<= 1;                    }                    a <<= 1;                }                table[i] = temp;            }        }        public ushort ComputeChecksum(byte[] bytes)        {            ushort crc = this.initialValue;            for (int i = 0; i < bytes.Length; ++i)            {                crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);            }            return crc;        }        public ushort ComputeChecksum(List<byte> listTemp)        {            byte[] bytes = listToBytes(listTemp);            ushort crc = this.initialValue;            for (int i = 0; i < bytes.Length; ++i)            {                crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);            }            return crc;        }        public byte[] ComputeChecksumBytes(byte[] bytes)        {            ushort crc = ComputeChecksum(bytes);            return BitConverter.GetBytes(crc);        }        public byte[] listToBytes(List<byte> listTemp)        {            int length = listTemp.Count();            byte[] bytes = new byte[length];            for (int i = 0; i < length; i++)            {                bytes[i] = listTemp[i];            }            return bytes;        }    }

 

最後,請叫我紅領巾

 

C# 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.