# Base Conversion – Handle upto 36 bases

Sometimes we need base conversion for different purpose. Here I have shown a technique that handles upto 36 bases. I implemented this using C++ language. But using this concept you could modify it and change it to any language.

The main concept is, to change base ‘X’ to base ‘Y’. First convert base ‘X’ to base ‘Decimal’. Then convert the ‘Decimal’ base to base ‘Y’.

/*BASE CONVERSION Programmer: Md. Mahmud Ahsan Description: Alpha Numeric Base Conversion Handle upto 36 bases */ #include <iostream> #include <string> using namespace std; int myPow(int number, int power){ int total=1; for (int i = 0; i < power; ++i) total *= number; return total; } void revStr(char *str){ char s[100]; int len = strlen(str)-1; for (int i = 0; str[i]; ++i) s[i] = str[len-i]; s[i] = '\0'; strcpy(str, s); } int otherToDec(char *str, int base){ int len = strlen(str) - 1; int alpha[100]; long long i, number, j=9; // j for alphabetical base digit for (i = 65; i < 65+26; ++i){ alpha[i] = ++j; // collect numeric data suppose A=10 } number = 0; for (i = 0; str[i]; ++i){ if (str[i] >= 'A' && str[i] <= 'Z') j = alpha[str[i]]; else j = str[i] - 48; number += j * myPow(base, len); --len; } return number; } char* decToOther(int number, int base){ char str[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char final[100]; int n, temp, j; j = -1; do{ temp = number % base; final[++j] = str[temp]; number = number / base; }while (number != 0); final[++j] = '\0'; revStr(final); return final; } int main(){ int number, base10, base, from, to; char str[100]; while (cin >> str >> from >> to){ base10 = otherToDec(str, from); strcpy(str, decToOther(base10 ,to)); cout << "Base 10: " << base10 << " " << "Base " << to << ": " << str << endl; } return 0; }

Thanks for the code, adapted this into Objective-C,

Here: https://gist.github.com/furkanmustafa/5660086