In: Computer Science
Given below is the code for the question. Please do rate the answer
if it helped. Thank you
import javax.swing.JOptionPane;
public class BaseConversion {
//checks if a given num is valid in the specified
base
private static boolean isValid(int base, String num)
{
char c;
for(int i = 0; i < num.length();
i++) {
c =
num.charAt(i);
switch(base)
{
case 2:
if(c != '0' || c != '1')
return false;
case 10:
if(c <= '0' || c >= '9')
return false;
case 16:
if(!((c >= '0' && c <= '9') || (c
>= 'A' && c <= 'F') || (c >= 'a' && c
<= 'f')))
return
false;
}
}
return true;
}
private static String convert(int src, String num, int
dest){
long deci = 0;
int digit;
char c;
int rem;
String str = "";
//first convert to decimal
for(int i = 0, j = num.length() -
1; j >= 0; j--, i++){
c =
num.charAt(j);
if(c >= '0'
&& c <= '9')
digit = c - '0';
else if(c >=
'A' && c <= 'F')
digit = c - 'A'+ 10;
else if(c >=
'a' && c <= 'f')
digit = c - 'a' + 10;
else
digit = 0;
deci = deci +
digit * (int)Math.pow(src, i);
}
//from decimal now convert to
dest
while(deci > 0){
rem = (int)
(deci % dest);
deci /=
dest;
if(rem >=
10)
c = (char)('A' + rem - 10);
else
c = (char)('0' + rem);
str = c +
str;
}
if(str.equals(""))
str = "0";
return str;
}
public static void main(String[] args) {
int src, dest;
String num;
String s;
s =
JOptionPane.showInputDialog("From which base do you want to convert
(2, 10 or 16): ");
src = Integer.parseInt(s);
s = JOptionPane.showInputDialog("To
which base do you want to convert (2, 10 or 16): ");
dest = Integer.parseInt(s);
s =
JOptionPane.showInputDialog("Enter a number in base " + src + ":
");
num = s;
if(isValid(src, num))
JOptionPane.showMessageDialog(null, "The number in base " + dest +
" is " + convert(src, num, dest));
else
JOptionPane.showMessageDialog(null, num + " is not a valid number
in base "+ src);
}
}