I have written this program to convert a decimal number to a number of any base. The resulting number has been put into an array and so can be of any size. But the decimal number that i take as input is limited by the range of int. What i want to do is to take it as a string and then change its base. The challenge is that i then cant divide and check for quotients and remainders as i can do with normal integers. What should i do?
This is what i got so far:
#include<iostream>
#include<cmath>
using namespace std;
int convert_to_base(int actual_number, int base, int **number);
int main()
{
int anumber = 0;//the actual number
int base;
bool negative = false;
cout<<"\nStarted Base Converter --- Kazi Asif Wadud --- Jan 20, 2005\n";
cout<<"\nUse Ctrl+C to exit";
while(true)
{
cout<<"\n\nEnter Number to convert: ";
cin>>anumber;
while(true)
{
cout<<"\t\tTo base: ";
cin>>base;
if(base >= 2)//Error checking for the base
break;
else
cout<<"Base must be greater than or equal 2\n";
}
cout<<"\t\t Result: ";
int *number;
int size;
if(anumber < 0)
{
negative = true;
anumber = -anumber;
}
size = convert_to_base(anumber, base, &number);
if(negative)
cout<<"-";
for(int i = 0; i < size; ++i)
cout<<number[i];
}
return 0;
}
int convert_to_base(int actual_number, int base, int **number)
{
//Makes the array 0 if the actual number is zero
if (actual_number == 0)
{
*number = new int;
*number[0] = 0;
return 1;
}
//Computing the required size of the array
//to hold the converted number
double size;
size = log10(actual_number) / log10(base) + 1;
//Allocating memory
*number = new int[size];
//The conversion takes place here
int i = size -1;
for(int quotient = actual_number; quotient > 0; quotient = quotient / base, --i)
*(*number + i) = quotient % base;
return (int)size;
}