什么是CRC16
CRC即循环冗余校验码(Cyclic Redundancy Check)也称为多项式码。它是一种数据传输检错功能,对数据进行多项式计算,并将得到的结果附在帧的后面,接收设备也执行类似的算法,进而可以保证在软件层次上数据传输的正确性和完整性。
CRC-16 | 0x8005 | x16 + x15 + x2 + 1 |
CRC-CCITT | 0x1021 | x16 + x12 + x5 + 1 |
CRC-DNP | 0x3D65 | x16 + x13 + x12 + x11 + x10 + x8 + x6 + x5 + x2 + 1 |
CRC-32 | 0x04C11DB7 | x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x1 + 1 |
项目 | 多项式 | 初始值 |
CRC-16/IBM | 0x8005 | 0x0000 |
CRC-16/MAXIM | 0x8005 | 0x0000 |
CRC-16/USB | 0x8005 | 0xFFFF |
CRC-16/MODBUS | 0x8005 | 0xFFFF |
CRC-16/CCITT | 0x1021 | 0x0000 |
CRC-16/CCITT-false | 0x1021 | 0xFFFF |
CRC-16/X25 | 0x1021 | 0xFFFF |
CRC-16/XMODEM | 0x1021 | 0x0000 |
CRC-16/DNP | 0x3D65 | 0x0000 |
MATLAB 代码
function [crc, hex] = crc16(packet,poly)
% Calculates CRC16/XModem for packet
% Input: byte content in an array
% https://www.lammertbies.nl/comm/info/crc-calculation
% J. Chen. Feb, 2020
crc = 0;
% crc = hex2dec('FFFF'); % for 0xFFFF version
for i = 1:length(packet)
crc = bitxor( crc, bitshift(packet(i),8) );
for bit = 1:8
if bitand( crc, hex2dec('8000') ) % if MSB=1
crc = bitxor( bitshift(crc,1), hex2dec(poly) );
else
crc = bitshift(crc,1);
end
crc = bitand( crc, hex2dec('ffff') ); % trim to 16 bits
end
end
hex = dec2hex(crc);
A = "12 12 83 5F 00 71 03 00 00 C8 92 8B D0 0D 00 00 00 00 03 66 00 B1 FF 00 " + ...
"00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 12 00 D2 03 0D 00 " + ...
"D2 03 00 00 00 00 00 00 C4 09 00 00 00 00 00 00 C4 09 00 00 00 00 00 00 00 00 " + ...
"01 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " + ...
"00 00 00 00 00 00 00 57 63 5C 63 00 00 12 00 17 09 00 0D 7A D4 03 32 00 00 00 00 00 " + ...
"00 00 00 32 13 00 00 00 EC FF 00 00 10 00 00 1A 00 00 00 19 00 00 00 00 00 00 00 00 C8 " + ...
"00 00 58 6D 00 00 00 00 00 00 00 00 00 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " + ...
"00 00 00 00 00 00 00 00 00 00 00 00 71 03 00 00";
PACK = regexp(A,'\s+','split');
[crc, hex] = crc16(hex2dec(PACK),'1021');
测试结果:
crc : 25641
hex : ‘6429’