计算机组成原理奇偶校验和海明校验

例:

数据             奇校验编码          偶校验编码

 

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_40799464/article/details/84840804