In: Computer Science
Write a c++ program to convert any decimal number to
either binary base or Hex base number system. Test your
program with the followings:
Convert 15 from decimal to binary.
Convert 255 from decimal to binary.
Convert BAC4 from hexadecimal to binary
Convert DEED from hexadecimal to binary.
Convert 311 from decimal to hexadecimal.
Convert your age to hexadecimal.
// C++ program to convert Decimal number to binary or hexadecimal
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int decimalNumber;
string convertedOutput;
int choice;
// input the decimal number
cout<<"Enter the decimal number to convert :";
cin>>decimalNumber;
// input the choice of conversion
cout<<"Enter the choice of conversion : 1. Binary 2. Hexadecimal : ";
cin>>choice;
cout<<"Decimal : "<<decimalNumber;
convertedOutput = "";
int rem;
int temp = decimalNumber;
if(choice == 1) // convert decimal to binary
{
// loop that continues till temp > 0
while(temp > 0)
{
rem = temp%2; // get the remainder left after multiplying temp by 2
temp = temp/2; // get the value left after multiplying temp by 2
// convert the rem to string
stringstream ss;
ss<<rem;
// add the rem to output
convertedOutput = ss.str() + convertedOutput;
}
cout<<" Binary : ";
}else // convert decimal to hexadecimal
{
// loop that continues till temp > 0
while(temp > 0)
{
rem = temp%16; // get the remainder left after multiplying temp by 16
temp = temp/16; // get the value left after multiplying temp by 16
// if rem < 10, then add the string equivalent to output
if(rem < 10)
{
stringstream ss;
ss << rem;
convertedOutput = ss.str() + convertedOutput;
}else // if rem >=10
{
// get the corresponding letter of the hexadecimal and add it to output
convertedOutput = (char)('F'-(15-rem)) + convertedOutput;
}
}
cout<<" Hexadecimal : ";
}
// output the converted value
cout<<convertedOutput<<endl;
return 0;
}
//end of program
Output:
Convert 15 from decimal to binary.
Convert BAC4 from hexadecimal to binary (decimal equivalent of BAC4 = 47812)
Convert 311 from decimal to hexadecimal.