final int MAX_BASE = 36;
final int NUM_CHARS = 65536;
final int SENTINEL_VALUE = 255;
int convertInputToComponentValue[MAX_BASE][];
for(int base = 2; base < MAX_BASE; base++) {
// Make it large enough to take any user input char
convertInputToComponentValue[base] = new int[NUM_CHARS];
// Default every input as an invalid character
for(int i = 0; i < NUM_CHARS; i++)
convertInputToComponentValue[base][i] = SENTINEL_VALUE;
// Map the relevant parts of '0'-'9', in the current base, to their integral value
// Eg; For base 2, only {'0' -> 0, '1' -> 1} are relevant
for(int input = 0; input <= Math.min(9,base-1); input++) {
int actualCharIndex = input + '0';
convertInputToComponentValue[base][actualCharIndex] = input;
}
// Map the relevant parts of 'A'-'Z', in the current base, to their integral value
// Eg; For base 13, only {'A' -> 10, 'B' -> 11, 'C' -> 12} are relevant
for(int input = 10; input < Math.min(MAX_BASE,base); input++) {
int actualCharIndex = input - 10 + 'A';
convertInputToComponentValue[base][actualCharIndex] = input;
// Hell, why not cover lower case as well
actualCharIndex = input - 10 + 'a';
convertInputToComponentValue[base][actualCharIndex] = input;
}
}
char[] convertComponentValueToOutput = new char[MAX_BASE];
for(int i = 0; i < 10; i++)
convertComponentValueToOutput[i] = i + '0';
for(int i = 10; i < MAX_BASE; i++)
convertComponentValueToOutput[i] = i - 10 + 'A';
// Now take an inputted value, and convert each char into component values
int inputBase = 5;
String inputString = "2130";
int totalValue = 0;
for(int i = 0; i < inputString.length(); i++) {
int componentValue = convertInputToComponentValue[inputBase][inputString.charAt(i)];
if( componentValue == SENTINEL_VALUE )
System.out.println("ARGH, the hills be swarming with orcs!");
totalValue *= inputBase;
totalValue += componentValue;
}
// In this case, each componentValue was: 2,1,3,0 so totalValue was: 2,11,58,_290_
int outputBase = 7;
StringBuffer reversedOutputString = new StringBuffer();
// Now output the value, as discrete component characters
do {
int componentValue = totalValue % outputBase;
totalValue -= componentValue;
totalValue /= outputBase;
char componentChar = convertComponentValueToOutput[componentValue];
reversedOutputString.add( componentChar );
} while(totalValue != 0);
// In this case, each componentValue was: 3, 6, 5
// So the proper output is "563"
// Double-check 5x7^2 + 6x7^1 + 3x7^0 = 245 + 42 + 3 = 290
String outputString = reversedOutputString.reverse.toString();