记录一段计算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