Categories

# Any Base to Any Base Conversion in Java

In Computer Science, quite often, we are required to convert numbers from one base to another. Numbers with bases 2, 8, 10 and 16 are commonly used.

Binary numbers include digits 0 and 1, and so they have base 2. Octal numbers have digits from 0 to 7, thus having base 8. Decimal numbers have digits from 0 to 9, thus have base 10. And hexadecimal numbers have digits from 0 to 9 and then A to F, thus having base 16.

Write a program in Java to convert a number in any base into another base, limiting the base value up to 16.

Example:
INPUT:
Enter the number: AF
Source base: 16
Destination base: 2
OUTPUT:
10101111

``````import java.io.*;
class AnyBase{
public static void main(String args[])throws IOException{
System.out.print("Enter the number: ");
n = n.toUpperCase();
System.out.print("Source base: ");
System.out.print("Destination base: ");
String r = convert(n, s, d);
System.out.println(r);
}
public static String convert(String n, int b1, int b2){
if(b1 == b2)
return n;
int deci = 0;
if(b1 != 10)
deci = getDecimal(n, b1);
String result = "";
if(deci == 0)
result = "0";
while(deci != 0){
int d = deci % b2;
if(d < 10)
result = d + result;
else if(d == 10)
result = 'A' + result;
else if(d == 11)
result = 'B' + result;
else if(d == 12)
result = 'C' + result;
else if(d == 13)
result = 'D' + result;
else if(d == 14)
result = 'E' + result;
else if(d == 15)
result = 'F' + result;
deci /= b2;
}
return result;
}
public static int getDecimal(String n, int base){
int d = 0;
int num = 0;
int p = 0;
for(int i = n.length() - 1; i >= 0; i--){
char ch = n.charAt(i);
switch(ch){
case '0':
num = 0;
break;
case '1':
num = 1;
break;
case '2':
num = 2;
break;
case '3':
num = 3;
break;
case '4':
num = 4;
break;
case '5':
num = 5;
break;
case '6':
num = 6;
break;
case '7':
num = 7;
break;
case '8':
num = 8;
break;
case '9':
num = 9;
break;
case 'A':
num = 10;
break;
case 'B':
num = 11;
break;
case 'C':
num = 12;
break;
case 'D':
num = 13;
break;
case 'E':
num = 14;
break;
case 'F':
num = 15;
break;
}
d += num * (int)Math.pow(base, p);
p++;
}
return d;
}
}``````

## 2 replies on “Any Base to Any Base Conversion in Java”

Sayan Ranasays:

Sir, a program is given which states that:
The Euler’s number e, is used as the base of natural logarithm. It can be approximated using the formula.
e=1+1/1!+1/2!+1/3!+…1/n!
WAP in JAVA that approximates e using a loop that terminates when the difference between two successive values of e
differ by less than 0.0000001
Can you please show me the code for this question?

This site uses Akismet to reduce spam. Learn how your comment data is processed.