Slip打包与解包及MATLAB程序
Slip打包与解包
基本原理
在数据包的头和尾加0xC0,如果数据中包含0xC0,用0xDB 0xDC代替,如果数据中包含0xDB,则用0xDB 0xDD代替。
SLIP打包程序(MATLAB)
function SlipOut = SlipPk(SlipIn)
xC0 = hex2dec('C0');
xDB = hex2dec('DB');
xDC = hex2dec('DC');
xDD = hex2dec('DD');
SlipInLen = length(SlipIn);
SlipOut = zeros(1,2*SlipInLen);
m = 1;
for k = 1:SlipInLen
if(SlipIn(k) == xC0)
SlipOut(m) = xDB;
SlipOut(m+1) = xDC;
m = m + 1;
elseif(SlipIn(k) == xDB)
SlipOut(m) = xDB;
SlipOut(m+1) = xDD;
m = m + 1;
else
SlipOut(m) = SlipIn(k);
end
m = m + 1;
end
SlipOut = [xC0 SlipOut(1:m-1) xC0];
end
SLIP解包程序(MATLAB)
function UnpkOut = SlipUnpk(UnpkIn)
xC0 = hex2dec('C0');
xDB = hex2dec('DB');
xDC = hex2dec('DC');
xDD = hex2dec('DD');
if(UnpkIn(1) ~= xC0 && UnpkIn(end) ~= xC0)
error('The slip package is wrong!');
end
UnpkInLen = length(UnpkIn);
UnpkOut = zeros(1,UnpkInLen-2);
m = 1;
k = 2;
while k < UnpkInLen
if(UnpkIn(k) == xDB && UnpkIn(k+1) == xDC)
UnpkOut(m) = xC0;
k = k + 2;
elseif(UnpkIn(k) == xDB && UnpkIn(k+1) == xDD)
UnpkOut(m) = xDB;
k = k + 2;
else
UnpkOut(m) = UnpkIn(k);
k = k + 1;
end
m = m + 1;
end
UnpkOut = UnpkOut(1:m-1);
end