Encoding and Decoding; Char to Hex -> Hex to Char
Mar 8, 2011 at 7:07am UTC
Hello folks,
I've been at this for quite some time and I'm at my wits end. I'm basically trying to convert a string or text file to hex. I think I got that part, but my issue is when I try to take the 'coded' txt file back to a normal easily readable file.
I have two functions listed below...
Is it possible to decode using fout.put(sprintf(&chEncoded[i],"%c", ch[i])); ? Or is my approach wrong all together?
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
int encodeTxt()
{
const int SIZE = 61;
const int chSize = 301;
char fileName[SIZE];
char chEncoded[chSize];
int i=0;
ifstream fin;
ofstream fout;
cout << "Enter text file name : " ;
cin >> fileName;
//Open the file
fout.open("coded.txt" );
fin.open(fileName, ios::in);
if (!fin)
{
cout << fileName << " could not be opened. \n" ;
return 0;
}
fin.getline(ch, chSize);
for (i = 0; i < 301; i++)
{
//fout.put(printf("%x",ch[i]));
fout.put(sprintf(&chEncoded[i],"%x" , ch[i]));
}
fin.close();
cout << "\nYour file has been encoded. " ;
return 0;
}
int decodeTxt()
{
const int SIZE = 61;
const int chSize = 301;
char fileName[SIZE];
char ch[chSize];
char chEncoded[chSize];
int i=0;
ifstream fin;
ofstream fout;
cout << "Enter Text file to be decoded: " ;
cin >> fileName;
//Open the file
fout.open("decoded.txt" );
fin.open(fileName, ios::in);
if (!fin)
{
cout << fileName << " could not be opened. \n" ;
return 0;
}
fin.getline(ch, chSize);
for (i = 0; i < chSize; i++)
//while (!fin.eof())
{
//fout.put(printf("%c",ch[i]));
//printf(&chEncoded[3],"%c", ch[3]);
fout.put(sprintf(&chEncoded[i],"%c" , ch[i]));
fin.getline(ch, chSize);
}
fin.close();
cout << "\nYour file has been decoded. " ;
return 0;
Sample txt file should be like this:
The rain in Spain is quite nice!
Thanks in Advance.
Topic archived. No new replies allowed.