「MATLAB」计算校验和 Checksum

什么是校验和

是一个算法,将一串数据累加,得到一个和。

MATLAB程序

function c_use = Checksum(packet)
%Checksum 求校验和
%   此处checksum提供详细说明

checksum = 0;

for i = 1:length(packet)
    value = hex2dec(packet(i));
    checksum = checksum + value;
end

c_hex = dec2hex(checksum);
c_use = c_hex(3:4);

end
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');
c_use = Checksum(PACK);

计算结果:’FA’

发表评论

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