Converting Hex to Binary Using In/Output Files
May 6, 2013 at 11:02pm UTC
Hi guys, I wrote a code a few days ago to prompt the user to enter "Hex" values and the program converts that "hex" value into a 8 digit binary number. I got they code to work successfully, but now I am trying to covert these "Hex" values from a input file (see below). I was only able to get the conversion to work for the first "hex" value though :(. Any tips or ideas on this?
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
char s[80];
int i,value,sum=0;
inFile.open("HexValuesSample.txt" );
outFile.open("HVS.txt" );
inFile >> s;
cout << endl << endl;
for (i=0;s[i]!=0;i++)
{
switch (s[i])
{
case '0' :
outFile << "0000" ;
value = 0;
break ;
case '1' :
outFile << "0001" ;
value = 1;
break ;
case '2' :
outFile << "0010" ;
value = 2;
break ;
case '3' :
outFile << "0011" ;
value = 3;
break ;
case '4' :
outFile << "0100" ;
value = 4;
break ;
case '5' :
outFile << "0101" ;
value = 5;
break ;
case '6' :
outFile << "0110" ;
value = 6;
break ;
case '7' :
outFile << "0111" ;
value = 7;
break ;
case '8' :
outFile << "1000" ;
value = 8;
break ;
case '9' :
outFile << "1001" ;
value = 9;
break ;
case 'a' :
case 'A' :
outFile << "1010" ;
value = 10;
break ;
case 'b' :
case 'B' :
outFile << "1011" ;
value = 11;
break ;
case 'c' :
case 'C' :
outFile << "1100" ;
value = 12;
break ;
case 'd' :
case 'D' :
outFile << "1101" ;
value = 13;
break ;
case 'e' :
case 'E' :
outFile << "1110" ;
value = 14;
break ;
case 'f' :
case 'F' :
outFile << "1111" ;
value = 15;
break ;
default :
outFile << "Invalid Input" ;
break ;
}
sum=sum+value;
outFile << " " ;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////
INPUT FILE:
00
00
08
00
40
40
02
02
00
88
C8
00
28
21
01
2A
08
00
00
14
15
01
00
00
20
20
20
09
01
00
////////////////////////////////////////////////////////////////////////////////
OUTPUT FILE:
0000 0000
May 6, 2013 at 11:23pm UTC
You might try reading in more than one token. Chances are it will involve another loop of some sort.
Topic archived. No new replies allowed.