Encoding

Hey, I wrote this code and trying to decode the codes that I have in my packets.dat file. In the packets.dat file, there are a bunch of binary codes and I'm trying to convert into the characters. Some reason I can get output to display when I run the code. Can someone tell me what's wrong with this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;

int BinToDec(int bin)
{
    int i, rem, dec = 0;
   //To convert to decimal.
    for (i = 0; i < 4; i++)
    {
        rem = bin % 10;
        dec += rem * pow(2, i);
        bin = bin / 10;
    }
    return dec;
}

string correction(string packet)
{
    string data;
    int i, len, p1, p2, p3, p4, err, pos;
    len = packet.length();
   //Calculating parity.
    p1 = (int)(packet[0] - '0') ^ (int)(packet[2] - '0') ^ (int)(packet[4] - '0') ^ (int)(packet[6] - '0') ^ (int)(packet[8] - '0') ^ (int)(packet[10] - '0');
    p2 = (int)(packet[1] - '0') ^ (int)(packet[2] - '0') ^ (int)(packet[5] - '0') ^ (int)(packet[6] - '0') ^ (int)(packet[9] - '0') ^ (int)(packet[10] - '0');
    p3 = (int)(packet[3] - '0') ^ (int)(packet[4] - '0') ^ (int)(packet[5] - '0') ^ (int)(packet[6] - '0') ^ (int)(packet[11] - '0');
    p4 = (int)(packet[7] - '0') ^ (int)(packet[8] - '0') ^ (int)(packet[9] - '0') ^ (int)(packet[10] - '0') ^ (int)(packet[11] - '0');
    //Forming error position in binary.
   pos = p4 * 1000 + p3 * 100 + p2 * 10 + p1;
   //Getting error index.
    err = BinToDec(pos);
    if (packet[err] == '1')
        packet[err] = '0';
    else
        packet[err] = '1';
   //Forming data word without parity.
    data = packet[11] + packet[10] + packet[9] + packet[8] + packet[6] + packet[5] + packet[4] + packet[2];
    return data;

}

int GrayToBin(string data)
{
   //To convert to binary from binary.
    int i, bin, len = data.length(), pos = (int)(data[0] - '0');
    bin = pos * pow(2, (len - 1));
    for (i = 1; i < len; i++)
    {
        pos = pos ^ (int)(data[i] - '0');
        bin += pos * pow(2, (len - 1 - i));
    }
    return bin;
}

int main()
{
    ifstream packets;
    packets.open("packets.dat"); //Opening file.
    string line, data;
    int bin, dec;
    cout<<"\nThe characters are (separated by space):\n";
    while (getline(packets, line)) //Reading till last line.
    {
        data = correction(line);
        bin = GrayToBin(data);
        dec = bin - 3; //Getting ASCII.
        cout<<(char)dec<<" ";
    }
    packets.close(); //Closing file.
    return 0;
}
Last edited on
Topic archived. No new replies allowed.