Anderson Green Anderson Green - 3 months ago 8
Java Question

Convert from one base to another in Java

Right now, I'm trying to find a way to convert a number from one base to another in Java, given a number, the base that the number is in, and the base to convert to.

public static void BaseConversion(String number, int base1, int base2){
//convert the number from one base to another
}


I found a solution for JavaScript, and I'm wondering if it would be possible to do something similar in Java:

function convertFromBaseToBase(str, fromBase, toBase){
var num = parseInt(str, fromBase); //convert from one base to another
return num.toString(toBase);
}

Answer

You could do

return Integer.toString(Integer.parseInt(number, base1), base2);