标签:
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校验码运算。
标签:
原文地址:http://www.cnblogs.com/Dukechris/p/4396375.html