Character Arrays Lab #5 Write a program that reads in two hexadecimal numbers fr
ID: 3593391 • Letter: C
Question
Character Arrays Lab #5 Write a program that reads in two hexadecimal numbers from a file, hex.txt, and prints out the sum of the two numbers in hexadecimal. From Wikipedia: "In mathematies and computer science, hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0-9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a-0 to represent values ten to fifteen. For example, the hexadecimal number 2AF3 is equal, in decimal, to THE SUM OF: (2x16") + (10×1620+(15 × 16') + (3x1OR10,995." For example, if the file contains: 45AF 12B3 ..and then your program will output (if you output the result in decimal): The decimal sum of 45AF and 12B3 is 22626. (To check your results, you can go to a hexadecimal calculator on the web. For example, http://www.csgnetwork.com/hexaddsubcale.htm) To solve this problem: Read the hexadecimal numbers as character arrays Convert the character arrays to numbers (by calling a function that takes the character array as a parameter, and returns an integer) Add the numbers to get a decimal sum EXTRA CREDIT: convert the sum to hexadecimal (by calling a function that fills a character array) a) b) c) d) PART II Assume that your file has an unknown number of hexadecimals. Modify/ Enhance /Change the program so that it prints the sum of all the numbers in the file.Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <cmath>
using namespace std;
int hexToDec(char *a)
{
int l,i;
int n=0,c=0;
l=strlen(a);
for(i=l-1;i>=0;i--)
{
if((a[i]>='A')&&(a[i]<='F'))
{
n=n+pow(16,c)*(a[i]-'A'+10);
}
else if((a[i]>='a')&&(a[i]<='f'))
{
n=n+pow(16,c)*(a[i]-'a'+10);
}
else
{
n=n+pow(16,c)*(a[i]-48);
}
c++;
}
return n;
}
char* decToHex(int n)
{
char *a;
int d;
a=new char[(int)log(n)+1];
while(n!=0)
{
d=n%16;
if(d<10)
{
strcat(a,(char *)(char)(48+d));
}
else
{
strcat(a,(char *)(char)(65+d-10));
}
n=n/16;
}
return a;
}
int main()
{
ifstream infile;
infile.open("hex.txt");
char data[100];
int sum=0;
if (!infile)
{
cerr<<"Unable to open the file.";
exit(-1);
}
while (infile >> data)
{
sum=sum+hexToDec(data);
}
cout<<"Sum = "<<sum<<endl;
cout<<"Sum = "<<decToHex(sum)<<endl;
infile.close();
return 0;
}