在串口编程中,肯定需要用到RCR验证码来判断接受到的数据是否正确,下面是百度的RCR验证码,测试正确的。

 1 private void CalculateCRC(byte[] pByte, int nNumberOfBytes, out byte hi, out byte lo)
 2         {
 3             ushort sum;
 4             CalculateCRC(pByte, nNumberOfBytes, out sum);
 5             lo = (byte)(sum & 0xFF);
 6             hi = (byte)((sum & 0xFF00) >> 8);
 7         }
 8 
 9         private void CalculateCRC(byte[] pByte, int nNumberOfBytes, out ushort pChecksum)
10         {
11             int nBit;
12             ushort nShiftedBit;
13             pChecksum = 0xFFFF;
14 
15             for (int nByte = 0; nByte < nNumberOfBytes; nByte++)
16             {
17                 pChecksum ^= pByte[nByte];
18                 for (nBit = 0; nBit < 8; nBit++)
19                 {
20                     if ((pChecksum & 0x1) == 1)
21                     {
22                         nShiftedBit = 1;
23                     }
24                     else
25                     {
26                         nShiftedBit = 0;
27                     }
28                     pChecksum >>= 1;
29                     if (nShiftedBit != 0)
30                     {
31                         pChecksum ^= 0xA001;
32                     }
33                 }
34             }
35         }