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); }
A class named Demo contains a function named 'base_convert' is defined. This function parses the integer from source base to the destination base, converts it into a string and returns it as output. In the main function, the value for number, for source base and for different destination bases are defined.
Decimal to Other Base SystemStep 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.
Steps To Convert From Base 10 to Base 2-Divide the given number (in base 10) with 2 until the result finally left is less than 2. Traverse the remainders from bottom to top to get the required number in base 2.
You could do
return Integer.toString(Integer.parseInt(number, base1), base2);
So with your function signature, in Java:
public String convertFromBaseToBase(String str, int fromBase, int toBase) { return Integer.toString(Integer.parseInt(str, fromBase), toBase); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With