「MATLAB」计算 CRC16 可配置多项式

什么是CRC16

CRC即循环冗余校验码(Cyclic Redundancy Check)也称为多项式码。它是一种数据传输检错功能,对数据进行多项式计算,并将得到的结果附在帧的后面,接收设备也执行类似的算法,进而可以保证在软件层次上数据传输的正确性和完整性。

CRC-160x8005x16 + x15 + x2 + 1
CRC-CCITT0x1021x16 + x12 + x5 + 1
CRC-DNP0x3D65x16 + x13 + x12 + x11 + x10 + x8 + x6 + x5 + x2 + 1
CRC-320x04C11DB7x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x1 + 1
项目多项式初始值
CRC-16/IBM0x80050x0000
CRC-16/MAXIM0x80050x0000
CRC-16/USB0x80050xFFFF
CRC-16/MODBUS0x80050xFFFF
CRC-16/CCITT0x10210x0000
CRC-16/CCITT-false0x10210xFFFF
CRC-16/X250x10210xFFFF
CRC-16/XMODEM0x10210x0000
CRC-16/DNP0x3D650x0000

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’

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注