in C++, Program 4: Conversion between Bases Write a program that will convert a decimal number to binary, octal, and hexadecimal (base 2, 8, and 16). Program Requirements: Prompt the user to input an integer value in decimal (base 10) and display the value in base 2, 8 and 16. Do NOT use built-in conversion methods for the conversion. You must do your own math to compute the values. Repeat the prompt and conversion until the user enters a sentinel value to quit. For example: Input a decimal: 23 23 in base 2: 10111 23 in base 8: 27 23 in base 16: 17 Additional Requirements: Do not allow negative or non-numeric input values from the user. The program should automatically display the conversion to the 3 required bases, don't make the user choose a base to convert to.
#include <iostream>
#include <sstream>
using namespace std;
void decimal_to_binary(int n)
{
int binary[32]; // binary array
cout << n << " in base 2 : ";
int i = 0; // counter for binary array
while (n > 0) {
binary[i] = n % 2; // storing the remainder in binary
array
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--) // print binary array in
reverse order
cout << binary[j];
cout << endl;
}
void decimal_to_octal(int n)
{
int octal[100]; // octal array
cout << n << " in base 8 : ";
int i = 0; // counter for octal array
while (n != 0) {
octal[i] = n % 8; // storing remainder in octal array
n = n / 8;
i++;
}
for (int j = i - 1; j >= 0; j--) // print octal array in
reverse order
cout << octal[j];
cout << endl;
}
void decimal_to_hexa(int n)
{
char hexaDeci[100]; // hexadecimal array
cout << n << " in base 16 : ";
int i = 0; // counter for hexadecimal array
while(n!=0)
{
int temp = 0;
temp = n % 16; // storing remainder
if(temp < 10) // check if temp < 10
{
hexaDeci[i] = temp + 48; // it gives numeric digit
i++;
}
else
{
hexaDeci[i] = temp + 55; // it gives alphabetic character
i++;
}
n = n/16;
}
for(int j=i-1; j>=0; j--) // print hexadecimal number array
in reverse order
cout << hexaDeci[j];
cout << endl;
}
int main()
{
string decimal; // take decimal value as a string
bool flag = true;
while(true)
{
cout << "Enter decimal (base 10) value : ";
cin >> decimal;
for (int i = 0; i < decimal.length(); i++)
if (isdigit(decimal[i]) == false) // check each element of
string
flag = false;
if (!flag) // sentinel value
break;
// object from the class stringstream
stringstream convert(decimal);
int n = 0;
convert >> n; // stream integer value to n
decimal_to_binary(n);
decimal_to_octal(n);
decimal_to_hexa(n);
cout << endl;
}
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.