Java36以下进制转换
功能为任意进制数与10进制相互转换
最近发现很多经常有各种进制转换的题,遂写了个万能版本,以10进制为媒介,实现的相互转换(方便以后偷懒),有改进的地方或者更好的方法欢迎交流
import java.util.Stack;
public class NumerationCalculate {
private static int inputNumeration = 16;//设置计数制
private final static char[] l = {'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 void setNum(int num) {
inputNumeration = num;
}
public static int toDec(String m) {
int flag = 1;
char[] s = m.toCharArray();
int dec=0;
try {
for(int i=s.length-1;i>=0;i--){
int x = 48;
if(s[i]>=48&&s[i]<=57) {
x = 48;
}
else if(s[i]>=65&&s[i]<=54+inputNumeration){
x = 55;
}
else if(s[i]>=97&&s[i]<=86+inputNumeration) {
x = 87;
}
else {
flag = 0;
throw new Exception("输入数字进制有误!程序终止!");
}
dec+=(s[i]-x)*(Math.pow(inputNumeration, s.length-i-1));
}
}catch(Exception e) {
System.out.println(e);
}
finally {
if(flag==0)
System.exit(0);
}
return dec;
}
public static String toTarget(int dec) {
String tar="";
Stack<Integer> s = new Stack<Integer>();
while(dec>=inputNumeration) {
s.push(dec%inputNumeration);
dec/=inputNumeration;
}
s.push(dec);
while(s.size()>0) {
String t = s.peek()<=9?(s.peek()+""):(l[s.peek()-10]+"");
tar+=t;
s.pop();
}
return tar;
}
}
是些很基础的东西。