循環冗餘碼CRC使用matlab實現

循環冗餘編碼
基本思想:發送端按照給定的規則,在k個信息比特後面增加L個按照某種規則計算的校驗比特;在接收端對收到的信息比特重新計算L個校驗比特。比較接收到的校驗比特和本地重新計算的校驗比特,如果相同則認爲傳輸無誤,否則認爲傳輸有誤。
循環冗餘編碼需要生成多項式,

CRC編碼程序

%CRC循環冗餘編碼函數
function crc_encode_scr=crc_encode(scr, poly)
%scr爲信息多項式係數向量,poly爲生成多項式係數向量[],例如,若係數爲1100,則輸入爲[1 1 0 0]
[M,N]=size(poly);
scrg=[scr zeros(1,N-1)];%在信息多項式係數後補零
[q,r]=deconv(scrg, poly);%多項式除法q中爲商,r爲餘數,此爲十進制多項式除法
r=abs(r);
for i=1:length(r)
    a=r(i);
    if(mod(a,2)==0)%將餘數變爲模二結果
        r(i)=0;
    else
        r(i)=1;
    end
end
crc=r(length(scr)+1:end);%獲取餘項
crc_encode_scr=bitor(scrg,r);%餘項加在信息位後面構成編碼


分析

deconv函數
不管是u,v還是q,r都是多項式的係數(所以,這是一個長除法的運算)。

>> help deconv
deconv - Deconvolution and polynomial division 反捲積和多項式除法

    This MATLAB function deconvolves a vector v out of a vector u using long
    division, and returns the quotient q and remainder r such that u = conv(v,q)+r.
    該函數使用長除法從向量u中解出向量v,並且返回商q和餘數r,使得u=conv(v,q)+r;,
    這裏conv是多項式乘法

    [q,r] = deconv(u,v)

bitor函數
返回兩數的異或值

>> help bitor
bitor - Bit-wise OR

    This MATLAB function returns the bit-wise OR of A and B.

    C = bitor(A,B)
    C = bitor(A,B,assumedtype)
    objout = bitor(netobj1,netobj2)

mod函數
返回餘數,取模。

>> help mod
mod - Remainder after division (modulo operation)

    This MATLAB function returns the remainder after division of a by m, where a is
    the dividend and m is the divisor.

    b = mod(a,m)

CRC解碼程序

%解碼
function [crc_decode_rev, error]=crc_decode(rev,poly)
%rev爲接收到的碼向量,poly爲生成多項式係數向量

[M,N]=size(poly);
[q r]=deconv(rev,poly);%得到長除法之後的商和餘數,十進制下
r=mod(abs(r),2);%轉化爲二進制下
if r==zeros(1,length(rev))
    error=0;
else
    error=1;
end
crc_decode_rev=rev(1:length(rev-N+1));%去掉後面校驗碼,得到原始信息比特

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章