rite a command line C++ program that will convert binary numbers to decimal and
ID: 3590404 • Letter: R
Question
rite a command line C++ program that will convert binary numbers to decimal and hexadecimal formats. The program should read the input from an input file and display the result in another output file. The first line of the input file contains a number N that represents the number of binary numbers to be converted. The file then contains N lines where each line is a binary number (which may contain a radix point). The output file contains N lines where each line starts with the binary number followed by the decimal equivalent followed by the hexadecimal equivalent
Explanation / Answer
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
static ofstream myfile;
//calucale decimal value
long calcDec(long number){
long remainder, base = 1, decimalNumber=0;
//cout << "The decimal equivalent of " << number ;
while (number > 0)
{
remainder = number % 10;
decimalNumber = decimalNumber + remainder * base;
base = base * 2;
number = number / 10;
}
//cout << " : " << decimalNumber << endl;
return decimalNumber;
}
//calculates hexadecimal value
char arr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
void calcHex(long n)
{
if (n > 0)
{
calcHex(n/16);
//cout << arr[n%16];
myfile << arr[n%16];
}
}
int main() {
ifstream in("input.txt");
myfile.open("output.txt");
if(!in) {
cout << "Cannot open input file. ";
return 1;
}
char str[10];
in.getline(str, 255);
int len = atoi(str) ;
while(len>0){
in.getline(str, 255);
long binary = atol(str);
myfile << binary << " ";
long decimalNumber=calcDec(binary);
myfile << decimalNumber << " ";
//cout << "Hexadecimal value is : ";
calcHex(decimalNumber);
myfile << " ";
len--;
}
return 0;
}
++++++++++++++++++++++++++++
input.txt :
4
11111111
101
11
1
output.txt
11111111 255 FF
101 5 5
11 3 3
1 1 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.