i have got working the algo of converting decimal number to any other base. what will be the algo for other way around?
i have got working the algo of converting decimal number to any other base. what will be the algo for other way around?
You should be able to use the same principles. You could probably use one function/algorithm to do both. Something like -
This is limited to properly converting bases below 10 and the amount of digits it can handle (which could be a problem using the lower bases).Code:#include <iostream> #include <cmath> using namespace std; int changebase(int num,int sourcebase,int destbase) { int power=0; int result=0; while(num) { result += num%destbase*pow(sourcebase,power++); num/=destbase; } return result; } int main() { cout << changebase(10111,2,10); return 0; }
zen
This code will allow you to convert between almost all bases
It uses 0-9 as digits then a-z so in theory it will work for up to base 36.
Hex aka base 16 uses 0-9,a-f
so base 17 will use 0-9,a-g
and base 18 will use 0-9,a-h
I haven't tested all those, but for base 2,8,10 and 16 it should do just fine.
It takes string as input so lenght is not an issue
If anyone sees a way i could optomize the conversion lemme know
Code:string ConvertBase(string number,int currentBase, int targetBase) { string temp = ""; string answer; char curr; int value; long int total=0; for( int i=number.length()-1 ; i>= 0 ; i--) { curr = number[i]; if( isdigit(curr) ) { value = curr - '0'; } else if( isalpha(curr) ) { curr = tolower(curr); value = curr - 'a' + 10; } else { cout << "Error in input"; return temp; } total += value * pow(currentBase,number.length()-i-1); } // cout << total << endl; // we now have the decimal value stored in total. time to convert it to the other base. int power = 0; while(total) { value = total % targetBase; total /= targetBase; if( value < 10 ) { temp += value + '0'; } else { temp += value - 10 + 'a'; } } for( i=1 ; i<=temp.length() ; i++) { answer += temp[temp.length() - i]; } return answer; }