# Thread: Base10 to Base n converter

1. ## Base10 to Base n converter

well I guess im a c/c++ noob (although im majoring in programming, im only a freshman) but anyway, after taking a class on binary, octal, hex, conversions,a dn that sort of thing, I decided to use my limited knowledge to whip up a converter. Tell me what ya think and throw in any suggestion you might have.

Code:
```//Decimal to Base 'n' Converter
//Converts any positive decimal number (up to 4,294,967,295) to base 'n'
//'n' being any base between 2 and 16
//Written by P4r4digm

#include <iostream>
using namespace std;
int main()
{
//declare variables
int convertFromCopy, digit, convertTo;
unsigned int convertFrom;
char playAgain = 'y';

//allow game to loop without ending
while (playAgain != 'n')
{
//delete pervious answer if run consecuteively

//Get user input
cout << "Enter the number you wish to convert: ";
cin >> convertFrom;
cout << "Enter the base to convert the number to(max: 16): ";
cin >> convertTo;

//createcopy of original input to display later
convertFromCopy = convertFrom;

//continue dividing until original input is 0
while (convertFrom != 0)
{
//calculate digit through use of modulo
digit = convertFrom % convertTo;

//declare conversion variable (from int to char)
int asciiConversion = 48;

//for loop converts digit from int 0-15 to char '0'-'9', 'A'-'F'
for (int i = 0; i < 16; ++i)
{
if(digit == i)
stringDigit = asciiConversion;

asciiConversion += 1;

//skip from 9 to A on the ascii table and continue
if (asciiConversion == 58)
asciiConversion = 65;
}

//tack on converted digit to the beginning of the answer string

//divide original input by conversion constant and loop
convertFrom /= convertTo;
}
//Show original input, base to be converted to, and converted number
//and ask to repeat
cout << convertFromCopy << " written in base " << convertTo << " is:\n" << answer << "\nAgain? (y/n)";
cin >> playAgain;
}
return 0;
}```

2. It's well done.

Code:
```>            //declare conversion variable (from int to char)
>            int asciiConversion = 48;
>
>            //for loop converts digit from int 0-15 to char '0'-'9', 'A'-'F'
>            for (int i = 0; i < 16; ++i)
>            {
>                if(digit == i)
>                stringDigit = asciiConversion;
>
>                asciiConversion += 1;
>
>                //skip from 9 to A on the ascii table and continue
>                if (asciiConversion == 58)
>                asciiConversion = 65;
>            }```
You could replace the above code with this:
Code:
```	if (digit < 10)
stringDigit = '0' + digit;
else
stringDigit = digit - 10 + 'A';```

Popular pages Recent additions