Java任意进制相互转换

/ java / 没有评论 / 436浏览

该算法最大支持62进制相互转换。

例如201314的62进制是Qn0,Qn0的十进制是201314

import java.util.LinkedList;
import java.util.List;

/**
 * 进制转换,最大支持62位,62位进制可以用于生成短连接
 * @author Administrator
 *
 */
public class Test016 {
	static char ch[] = {'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',
						'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 main(String args[]){
		long a = Long.parseLong("201314");
		System.out.println(toSystem(a, 62));
		System.out.println(toDecimalSystem("Qn0", 62));
	}
	
	//10进制转成n进制
	public static String toSystem(long number,int n){
		if(number==0)
			return "0";
		if(n>62)
			return "最大进制为62位";
		StringBuffer result = new StringBuffer();
		List<Integer> mods = new LinkedList<Integer>();
		mods.add((int) (number % n));
		number = number/n;
		if(number/n==0)
			  mods.add((int) (number % n));
		while(number/n!=0){
			  int mod = (int) (number % n);
			  mods.add(mod);
			  number = number/n;
			  if(number/n==0)
				  mods.add((int) (number % n));
		}
		for(int i=mods.size()-1;i>=0;i--){
			if(i!=(mods.size()-1)||mods.get(i)!=0)
				result.append(ch[mods.get(i)]);
			//System.out.println(mods.get(i));
		}
		return result.toString();
	}
	
	//n进制转成10进制
	public static String toDecimalSystem(String number,int n){
		String result = "";
		int length = number.length();
		long temp = 0;
		for(int i=0;i<length;i++){
			if(isLegal(number.charAt(i), n)){
				temp = (long) (temp + toInt(number.charAt(i)) * Math.pow(n, (length-i-1)));
				/*System.out.println(number.charAt(i));
				System.out.println(toInt(number.charAt(i)));*/
			}else{
				result = "不合法字符";
				return result;
			}
		}
		result = String.valueOf(temp);
		return result;
	}
	
	//ascii转n进制下的数
	public static int toInt(char ch){
		int c = ch;
		int result = -1;
		if(c>=48&&c<=57){
			result = c - 48;
		}else if(c>=97&&c<=122){
			result = c - 97 + 10;
		}else if(c>=65&&c<=90){
			result = c - 65 + 36;
		}
		return result;
	}
	//判断字符是否在n进制里面
	public static boolean isLegal(char ch,int n){
		boolean result = false;
		int c = ch;
		if(n<2){
			result = false;
		}else if(n>=2&&n<=10){
			if(c>=48&&c<=(47+n))
				result = true;
		}else if(n>10&&n<=36){
			if(c>=48&&c<=57){
				result = true;
			}
			if(c>=97&&c<=(97-10+n-1)){
				result = true;
			}
		}else if(n>36&&n<=62){
			if(c>=48&&c<=57){
				result = true;
			}
			if(c>=97&&c<=122){
				result = true;
			}
			if(c>=65&&c<=(65-36+n-1)){
				result = true;
			}
		}else{
			result = false;
		}
		return result;
	}
}

点击这里给我发消息
嘿!有什么能帮到您的吗?