MFC 计算CRC16校验码

记录一段计算CRC16校验码的代码

 1 unsigned short CtestCRCDlg::CRCAlgorithm(unsigned char *buffer, int len)//crc函数得到10进制数
 2 {
 3     if(buffer && len > 0)
 4     {
 5         unsigned short crc_value = 0xFFFF;          
 6         while (len--)
 7         {
 8             crc_value = (crc_value >> 8) ^ crc16_ccitt_table[(crc_value ^ *buffer++) & 0xff];
 9         }
10         return (unsigned short)(crc_value);
11     }
12     return 0;
13 }
14 
15 int CtestCRCDlg::S2H( CString s, unsigned char *h)//把cstring类型转换为byte[]类型
16 {
17     char a[0x400];
18     //_tcscpy((char *)a, s.GetBuffer(0));//vs2012 使用新函数
19     _tcscpy_s((char *)a, sizeof(a) / sizeof(a[0]), s.GetBuffer(0));
20     s.ReleaseBuffer();
21 
22     size_t i;
23     size_t l;
24     int count = 0;
25     char c, x;
26 
27     l = _tcslen(a);
28 
29     for(i = 0; i < l; i++)
30     {
31         c = a[i];
32         if(c >= '0' && c <= '9')
33         {
34             x = c - '0';
35         }else if (c >= 'a' && c <= 'f')
36         {
37             x = c - 'a' + 10;
38         }else if (c >= 'A' && c <= 'F')
39         {
40             x = c - 'A' + 10;
41         }else
42         {
43             continue;
44         }
45         if(!(count % 2))
46         {
47             h[count / 2] = (x << 4);
48         }else
49         {
50             h[count / 2] |= x;
51         }
52         count++;
53     }
54     return count / 2;
55 }
56 
57     //调用方法
58     CString str = "01100050000e";
59     CString m_crc;
60     BYTE buff[6];
61     S2H(str, buff);
62     WORD wCRC = CRCAlgorithm(buff, 6); //56385
63     m_crc.Format( "%x", wCRC);
64     AfxMessageBox(m_crc); //dc41

 

转载于:https://www.cnblogs.com/ckrgd/p/8435251.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值