CRC校驗程序1:CRC循環冗余校驗碼計算


        CRC全稱Cyclic Redundancy Check,中文稱為循環冗余檢查。它是一種數據傳輸檢錯的機制,能夠對數據進行多項式計算,並將得到的結果與接收設備共享,保證數據傳輸的正確性和完整性。

        算法流程如下:

1. Load a 16-bit register with FFFF hex (all ‘1’s). Call this the CRC register.

2. Exclusive OR the first 8-bit byte of the message with the low-order byte of the 16-bit CRC register, putting the result in the CRC register.

3. Shift the CRC register one bit to the right (toward the LSb), zero-filling the MSb. Extract and examine the LSb.

4. If the LSb is ‘0’, repeat Step 3 (another shift). Otherwise, if the LSB is ‘1’, Exclusive OR the CRC register with the polynomial value 0xA001 (1010 0000 0000 0001).

5. Repeat steps 3 and 4 until eight shifts have been performed. When this is done, a complete 8-bit byte will have been processed.

6. Repeat steps 2 through 5 for the next 8-bit byte of the message. Continue doing this until all bytes have been processed.

7. The final content of the CRC register is the CRC value.

8. When the CRC is placed into the message, its upper and lower bytes must be Swapped to let the High 8-bit first and followed by low 8-bit.

        翻譯成中文:

1. 載入一個16位的寄存器,賦值為FFFF,叫做CRC寄存器。

2. 將信息中的第一個8位字節同寄存器的低8位進行異或運算,結果保存在CRC寄存器中。

3. CRC寄存器向右移動1位,缺位補0,同時檢查最低位。

4. 如果最低位是0,重復步驟3,如果為1,則CRC寄存器與十六進制值A001進行異或運算。

5. 重復步驟3和4直到8次移位結束,如此處理完一個字節的數據啦。

6. 重復步驟2到步驟5,運算信息中之后的全部8位字節。

7. 最后的CRC寄存器值就是CRC值。

8. 交換CRC寄存器值的高八位和低八位,放在信息中。

        這一次,寫出一個函數,進行對一個8位字節進行CRC運算。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace CRC
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine(CalaCRC.CRCCalculating(0xAE0F));         
14         }
15     }
16     class CalaCRC
17     {
18         public static UInt32 CRCCalculating(UInt32 CRCByte){
19             UInt32 CRCRegister = 0xFFFF;
20             CRCRegister = (CRCByte ^ CRCRegister);
21 
22             CRCRegister = CRCRegister >> 1;
23             int i = 1;
24 
25             for (; i <= 8; i++)
26             {
27                 if (CRCRegister % 2 == 0)
28                 {
29                     CRCRegister = CRCRegister ^ 0xA001;
30                     i--;
31                 }
32                 else
33                 {
34                     CRCRegister = CRCRegister >> 1;
35                 }
36             }
37             return CRCRegister;
38         }
39     }
40 }

        其中CalaCRC類中的靜態函數,對輸入的字節產生一個經過CRC運算的輸出。
        下一篇文章,實現通過控制台調用exe讀取文件來實現CRC校驗碼運算。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM