1. 程式人生 > >計算機組成原理奇偶校驗和海明校驗

計算機組成原理奇偶校驗和海明校驗

例:

資料             奇校驗編碼          偶校驗編碼

 

01110101      001110101         101110101

00000000      100000000         000000000

 

 

例:設有一個 7 位資訊碼位 0110001,求它的海明碼。

解: n=7,根據海明不等式,可求得校驗位最短長度 k=4。

其海明碼先表示如下:

海明碼位號:H11 H10 H9 H8 H7 H6 H5 H4 H3 H2 H1 海明碼:   0   1  1  P4  0 0  0 P3 1 P2  P1

按偶校驗寫出校驗方程為:

 

  1. ⊕H3⊕H5 ⊕H7 ⊕H9⊕H11=0        (P1=H1) H2 ⊕H3⊕ H6⊕H7 ⊕H10⊕H11=0      (P2=H2) H4⊕H5⊕ H6⊕H7=0        (P3=H4) H8⊕H9⊕ H10⊕H11=0      (P4=H8)可得:P1=0、P2=0、P3=0、P4=0,所以 0110001 的海明碼為

01100000100

 

程式碼:

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int arr[20];
int thexor[4][5]=
{
    3,5,7,9,11,
    3,6,7,10,11,
    5,6,7,12,13,
    9,10,11,12,13,
};

int main()
{
    string str;
    cout<<"請輸入選擇那一種校驗碼:1,奇偶校驗;2,海明校驗;"<<endl;
    int xuanze;
    cin>>xuanze;
    cout<<"請輸入資料"<<endl;
    cin>>str;
    if(xuanze==1)
    {
        int temp=0;
        for(int i=0;i<str.length();i++)
            if(str[i]=='1')temp++;
        cout<<"奇校驗編碼:";
        if(temp%2==0)cout<<"1";
        else cout<<"0";
        cout<<str<<endl;
        cout<<"偶校驗編碼:";
        if(temp%2==0)cout<<"0";
        else cout<<"1"<<endl;
        cout<<str<<endl;
    }
    else
    {
        int n=str.length();
        int k=1;
        while(n+k+1>pow(2,k))
            k++;
        if(k>4){cout<<"輸入超限,請重新輸入"<<endl;return 0;}
        int c=k-1,d=0;//cout<<c<<endl;
        char str1[20];
        for(int i=k+n-1;i>=0;i--)
        {
            if(pow(2,c)==i+1)
                str1[i]=0,c--;
            else
                str1[i]=str[d++];
        }
        /*
        for(int i=0;i<k+n;i++)
        	cout<<str1[i];
			cout<<endl;*/ 
        for(int i=0;i<k;i++)
        {
            int now=str1[ thexor[i][0]-1 ]-'0';
            for(int j=1;j<5;j++)
                if(thexor[i][j]<k+n)
                    now^=(str1[thexor[i][j]-1]-'0');
            int the=pow(2,i)-1;
            str1[the]=now+'0';
        }
        cout<<"海明校驗碼為:"<<endl;
        for(int i=k+n-1;i>=0;i--)
            cout<<str1[i];
        cout<<endl;
    }
    return 0;
}