直接看代码, 以实现25进制的数转化为16进制的数为例:
思路是:经过一次转换,先将25进制的数转化为10进制,再将10进制的数转化为16进制;
如有问题,欢迎指正;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;
public class Practise {
private static long tenToAny(long middle) {
// 10进制到任意进制,以16进制为例;
double origin = (double) middle;
List<Integer> a = new ArrayList<>();
while (origin > 0) {
// 这里的16可以替换成任意你要的进制;
// 获取最大的幂, 如m*16^x
int x = (int)(Math.log(origin) / Math.log(16));
// 获取该幂的乘数
int m = (int)(origin / Math.pow(16, (double)(x)));
a.add(m);
// 取余,进行递归运算
origin = origin % (m * Math.pow(16, (double)(x)));
}
StringBuilder c = new StringBuilder();
for (Integer each:a
) {
c.append(each.toString());
}
return Long.parseLong(c.toString());
}
public static void main(String[] args) {
String origin = "A5F1065SB";
long ten = Practise.anyTo10(origin);
System.out.print("十进制数为: " + Long.toString(ten));
System.out.println(tenToAny(ten));
}
private static int anyTo10(String origin) {
// 任意进制如25进制的数转换为10进制
// aka公式:m = a1*25^n-1 + a2*25^n-2 + ... + an*25^0
String[] elements = origin.split("");
int mm = 0;
for (int i=0;i<=elements.length - 1; i++
) {
Character c = elements[i].charAt(0);
System.out.print(getByteNum(c) + "\n");
mm += getByteNum(c) * Math.pow(25, elements.length - 1 - i);
}
System.out.println(mm);
return mm;
}
private static int getByteNum(Character ch) {
// 返回任意字符的numeric value, 如A是10,B是11,1就是1等
return Character.getNumericValue(ch);
}
}
网友评论