Write a command line C/C++ program that will convert binary numbers to decimal a
ID: 3590436 • Letter: W
Question
Write a command line C/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 <bits/stdc++.h>
#include<iostream>
#include <fstream>
using namespace std;
double binaryToDecimal(string binary, int len)
{
// Fetch the radix point
size_t point = binary.find('.');
// Update point if not found
if (point == string::npos)
point = len;
double intDecimal = 0, fracDecimal = 0, twos = 1;
// Convert integral part of binary to decimal
// equivalent
for (int i = point-1; i>=0; --i)
{
// Subtract '0' to convert character
// into integer
intDecimal += (binary[i] - '0') * twos;
twos *= 2;
}
// Convert fractional part of binary to
// decimal equivalent
twos = 2;
for (int i = point+1; i < len; ++i)
{
fracDecimal += (binary[i] - '0') / twos;
twos *= 2.0;
}
// Add both integral and fractional part
return intDecimal + fracDecimal;
}
string conv(string number, int startBase, int endbase);
long long power(int num, int pow);
int main()
{
string file;
cout << "Enter Input File Name : ";
cin >> file;
ifstream in1(file);
int i = 0, x, y;
if (in1.is_open())
{
int n;
in1 >> n;
cout << n << endl;
string P[n];
for(int i = 0; i < n; i++)
{
in1 >> P[i];
string t = P[i]+ " "+conv(P[i],2,10)+" "+conv( P[i],2,16 );
cout<<t<<endl;
P[i]=t;
}
fstream file1; //object of fstream class
//opening file "sample.txt" in out(write) mode
file1.open("sample.txt",ios::out);
if(!file1)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
cout<<"File created successfully."<<endl;
//write text into file
for(int i=0; i<n; i++){
file1>>P[i];
}
//closing the file
file1.close();
}
in1.close();
return 0;
}
string conv(string number, int startBase, int endBase){
if(startBase > 16 || endBase > 16) return "BASE ERROR";
char NUMS[] = "0123456789ABCDEF";
string result = "";
int temp = 0, x;
bool found = false;
for(int i = 0; i < number.length(); i++){
for(x = 0; x < startBase; x++){
if(NUMS[x] == number[number.length()-(i+1)]){
found = true;
break;
}
}
if(!found) return "NUMBER ERROR";
temp += (x*power(startBase, i));
}
do{
result.push_back(NUMS[temp%endBase]);
temp /= endBase;
}while(temp != 0);
return string(result.rbegin(), result.rend());
}
long long power(int num, int pow){
if(pow == 0) return 1;
return num*power(num, pow-1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.