I have to write a program that converts a decimal number to a binary,octal, or hexadecimal number. The number are coming out correct but backwards. Like if the answer should be 123, it comes out as 321. I've been trying to fix this for a long while now and can't seem to get the right code. Any help would be appreciated.
As you are going to derive the digits from the right, but write them back from the left, you probably have to store them in something (e.g. a string as below), adding each new one to the left, before you write them out as below.
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string converted =""; // stores result; appending to start for each new digit
int decimal, remainder, choice;
cout << "Please enter a decimal: ";
cin >> decimal;
cout << "Convert the number from decimal into:\n0 Binary\n1 Octal\n2 Hexadecimal\n";
cin >> choice;
switch (choice)
{
case 0:
while (decimal > 0)
{
remainder = decimal % 2;
decimal /= 2;
converted = char( remainder + '0' ) + converted;
}
break;
case 1:
while (decimal > 0)
{
remainder = decimal % 8;
decimal /= 8;
converted = char( remainder + '0' ) + converted;
}
break;
case 2:
while (decimal > 0)
{
remainder = decimal % 16;
decimal /= 16;
if (remainder > 9)
converted = char('A' + remainder - 10) + converted;
else
converted = char( remainder + '0' ) + converted;
}
break;
default:
cout << "Invalid.";
}
// Now write result
cout << converted;
return 0;
}
Note: you could also improve your code quite a lot by shortening it. You essentially have the same operation written out three separate times (but for different base b, where b is 2,8 or 16). You could put the switch block inside here. There is nothing stopping you using any other number base.