matlab实现CRC

适用于任何小于等于32位的CRC校验

function crcout = crcX(datain,tempstr,initdata,refin,refout,xorout)
%cala crc
%author ******
%parameter: initdata --xor the fisrt reg; refin --- the datain need reflect
%refout: out crc need reflect; xorout--- crc reg xor xorout
mcrctemp = uint32(bin2dec(tempstr));
len = length(tempstr);
size = length(datain);
for i = 0:(fix(len/8)+1)
    datain(end+1) = 0;
end
if refin ~= 0
    datain = reflect(datain , 8);
end
%andvalue = num2str(uint8(zeros(1,len+1)));
%andvalue(len+1) = '1';
andvalue = bitshift(1,len);
midout = uint32(0);
for i = 0:(((size*8)-1)+len)
    midout = bitshift(midout,1);  
    if bitand(datain((fix(i/8)+1)),bitshift(1,7-rem(i,8))) ~= 0
        midout = bitor(midout,1);
    end
    if i == len-1
        midout = bitxor(midout,initdata);
    end
    if bitand(midout,andvalue)~=0 
        midout = bitxor(midout,mcrctemp);
    end
% dec2bin(midout)
end
if refout ~= 0
    midout = reflect(midout,len);
end
midout = bitxor(midout,xorout);
andvalue = bitshift(4294967295,len-32);
crcout = bitand(midout,andvalue);
end   
function outdata=reflect(data,bitnum)
%reflect this data
%paramter explain: bitnum reflect bit number
size=length(data);
outdata = zeros(1,size);
mvalue = bitshift(4294967295,bitnum);
for i = 1:size
    outdata(i) = data(i);
    outdata(i) = bitand(outdata(i),mvalue);
    for j=0:(bitnum-1)
        if bitand(data(i),bitshift(1,j)) ~= 0
            outdata(i) = bitor(outdata(i),bitshift(1,bitnum -1 - j));
        end
    end
end
end

你可能感兴趣的:(matlab-CRC)