Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from one base to another in Java

Tags:

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); } 
like image 401
Anderson Green Avatar asked Mar 31 '13 22:03

Anderson Green


People also ask

How do you convert a number from one base to another in Java?

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.

How do you convert from one base to another base?

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.

How do you convert numbers to base 2?

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.


1 Answers

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); } 
like image 108
nullpotent Avatar answered Sep 21 '22 12:09

nullpotent