C++ CODE PLEASE: INCLUDE COMMENTS Write a program that reads in hexadecimal numb
ID: 3910490 • Letter: C
Question
C++ CODE PLEASE: INCLUDE COMMENTS
Write a program that reads in hexadecimal numbers from a file, hex.txt, and prints out the sum of the numbers in hexadecimal.
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 × 163) + (10 × 162) + (15 × 161) + (3 × 160), or 10,995.”
Assume that your file has an unknown number of hexadecimals.
Write a program so that it prints the sum of all the numbers in the file.
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
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
input file: hexin.txt
=================
AB
12
============
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
long hexToDeci(char *hex);
void deciToHex(long deci, char *hex);
int main(){
string filename ;
char hex[10];
long deci;
long sum = 0;
cout << "Enter input filename: ";
cin >> filename;
ifstream infile(filename.c_str());
if(infile.fail()){
cout << "ERROR: could not open input file " << filename << endl;
exit(1);
}
while(infile >> hex){
deci = hexToDeci(hex);
sum += deci;
}
infile.close();
deciToHex(sum, hex); //convert sum to hexa
cout << "The sum is " << hex << "(hexadecimal)" << endl;
}
long hexToDeci(char *hex){
int value;
char ch;
long deci = 0;
long power = 1;
for(int i = strlen(hex)-1; i >= 0; i--){
ch = hex[i];
if(ch >='0' && ch <= '9')
value = ch - '0';
else if(ch >='A' && ch <= 'F')
value = ch - 'A' + 10;
else if(ch >='a' && ch <= 'f')
value = ch - 'a' + 10;
else
value = 0;
deci += value * power;
power *= 16; //get next power of 16
}
return deci;
}
void deciToHex(long deci, char *hex){
char s[10] = "";
int rem;
char ch;
int i = 0;
while(deci > 0){
rem = (int) deci % 16;
if(rem < 10)
ch = '0' + rem;
else
ch = 'A' + rem - 10;
s[i++] = ch;
deci = deci / 16;
}
if(s[0] == '')
strcpy(hex, "0");
else{
s[i] = '';
hex[i] = '';
i--;
//copy the reversesd string into hex
for(int j = 0; i >= 0; i-- ,j++)
hex[j] = s[i];
}
}
output
-----
Enter input filename: hexin.txt
The sum is BD(hexadecimal)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.