Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Reading it from the file C ++ Write a program that reads in two hexadecimal numb

ID: 3853033 • Letter: R

Question

Reading it from the file C ++ Write a program that reads in two hexadecimal numbers from a file, hex, data, and prints out the sum of the two numbers in hexadecimal. (As noted in class, first do this without using a file and by reading using the cin > > command) From Wikipedia: "In mathematics 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-f) to represent values ten to fifteen. For example, the hexadecimal number 2AF3 is equal, in decimal, to (2 times 16^3) + (10 times 16^2) + (15 times 16^1) + (3 times 16^0) or 10, 995." For example, if the file contains: 45AF 12B3 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, http: //www.csgnetwork.com/hexaddsubcalc.html) To solve this problem: a) read the hexadecimal numbers as character arrays b) convert the character arrays to numbers (by calling a function that takes the character array as a parameter, and returns an integer) c) add the numbers to get a decimal sum d) EXTRA CREDIT: convert the sum to hexadecimal (by calling a function that fills a character array) Assume that your file has an unknown number of hexadecimals. Change your program so that it prints the sum of all the numbers in the file.

Explanation / Answer

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc,char ** argv) {
if(argc <= 1) {
cout<<"Enter a file name please";
exit(0);
} else {
fstream in;
in.open(argv[1],fstream::in | fstream::out | fstream::binary);
string input;
unsigned int v;
unsigned int print;
unsigned int g;
int iter;
for(iter = 0; input!="save";){
cout<<"Hex Edit("<<argv[1]<<"): ";
cin>>input;
if(input == "read"){
cout<<"Enter Offset: ";
cin>>hex>>v;
in.seekg(v);
print=in.get();
g=in.tellg();
cout<<"Value at offset("<<hex<<g<<"): "<<hex<<print;
cout<<endl;
}
if(input == "write"){
cout<<"Enter Offset: ";
cin>>hex>>v;
in.seekp(v);
cout<<"Enter Value: ";
cin>>hex>>v;
in.put(v);
}
} else if(input == "save") {
in.close();
}
cout<<endl;
}
}
return 0;
}