I'm having issues converting 12 into hamming code using C++

112 Views Asked by At

I'm having issues converting 12 into hamming code. I've verified the that it's correctly converting the number into binary (base-2), and now when I attempt to use the formula to convert the security bits correctly, it's giving me a different answer than what I should be getting.


#include <iostream>
#include <vector>
using namespace std;

void print(vector<int> x){
   
    for (int i = 0; i < x.size(); i++){
        cout << x[i];
    }
    cout << endl;
  
}

vector<int> correctCode(vector<int> x, int pos){
    vector<int> correctedCode = x;
    cout << "Wrong Code: ";
    print(x);
    
    if (correctedCode[pos] == 0){
        correctedCode[pos] = 1;
    }
    else
    {
        correctedCode[pos] = 0;
    }
    cout << "Corrected Code: ";
    print(correctedCode);
    return correctedCode;
}

//Convert
void convertBinary(int val){
    vector<int> binaryVal;
    vector<int> binaryBase = {64,32,16,8,4,2,1};
    for (int i=0; i < 7; i++){
        if(val >= binaryBase[i]){
            val -= binaryBase[i];
            binaryVal.push_back(1);
        }
        else{
            binaryVal.push_back(0);
        }
    }
    //Security 1
    binaryVal[0] = (binaryVal[2]+binaryVal[4]+binaryVal[6])%2;

    
    //Security 2
    binaryVal[1] = (binaryVal[2]+binaryVal[5]+binaryVal[6])%2;
    
    //Security 3
    binaryVal[3] = (binaryVal[4]+binaryVal[5]+binaryVal[6])%2;
   
    
    
    print(binaryVal);
}

int main(int argc, const char * argv[]) {
    

    cout << "12 = ";
    convertBinary(12);
    cout << endl;

   
}

Binary = 0001100

12 = 1001100(Is what I'm getting) Should be = 0111100 (from what my professor mentioned)

1

There are 1 best solutions below

0
Urban-Programmer On

I made an error when converting binary to hamming. I just assigned the last four digits of the binary code to message bits, then inserted the message bits after properly calculating the security bits.

    
    int m3,m5,m6,m7;
    m3 = binaryVal[3];
    m5 = binaryVal[4];
    m6 = binaryVal[5];
    m7 = binaryVal[6];
    
    binaryVal[0] = (m3+m5+m7)%2;
    binaryVal[1] = (m3+m6+m7)%2;
    binaryVal[3] = (m5+m6+m7)%2;
    
    binaryVal[2] = m3;
    binaryVal[4] = m5;
    binaryVal[5] = m6;
    binaryVal[6] = m7;