试试下面的代码,可以把10进制转换为2~36之间的任意进制,也可以把2~36之间的任意进制数转成10进制。
百度勿吞!!!
public class NumberToNumber {
public static String[] arr = {"0","1","2","3","4","5","6","7","8",
"9","A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z"};
public static String numbers = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public String tenToAll(int num,int base){
if(base < 2 || base > arr.length){
return String.valueOf(num);
}
String result = "";
do{
result = arr[num%base] + result;
num = (num - num%base)/base;
}while(num/base != 0);
result = num==0?result:arr[num] + result;
return result;
}
public int allToTen(String num,int base) throws Exception{
num = num.toUpperCase();
int d = 0;
int len = num.length();
for(int i=0;i
int val = numbers.indexOf(sub);
if(val == -1 || val > base){
throw new Exception();
}
d += val * Math.pow(base, len - i - 1);
}
return d;
}
public static void main(String[] args) {
NumberToNumber n = new NumberToNumber();
try {
String num = "123322";
int result = n.allToTen(num, 4);
System.out.println(result);
System.out.println(n.tenToAll(result, 4));
} catch (Exception e) {
System.err.println("非法数字!");
}
}
}
可以把10进制转换为2~36之间的任意进制,也可以把2~36之间的任意进制数转成10进制。
百度勿吞!!!
public class NumberToNumber {
public static String[] arr = {"0","1","2","3","4","5","6","7","8",
"9","A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z"};
public static String numbers = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public String tenToAll(int num,int base){
if(base < 2 || base > arr.length){
return String.valueOf(num);
}
String result = "";
do{
result = arr[num%base] + result;
num = (num - num%base)/base;
}while(num/base != 0);
result = num==0?result:arr[num] + result;
return result;
}
public int allToTen(String num,int base) throws Exception{
num = num.toUpperCase();
int d = 0;
int len = num.length();
for(int i=0;i
int val = numbers.indexOf(sub);
if(val == -1 || val > base){
throw new Exception();
}
d += val * Math.pow(base, len - i - 1);
}
return d;
}
public static void main(String[] args) {
NumberToNumber n = new NumberToNumber();
try {
String num = "123322";
int result = n.allToTen(num, 4);
System.out.println(result);
System.out.println(n.tenToAll(result, 4));
} catch (Exception e) {
System.err.println("非法数字!");
}
}
}