任意进制与10进制的互转 62进制Demo

任意进制转换为10进制

假设一个R进制的数为 An-1An-2An-3…A0
将其转换为10进制的公式为
y = An-1*Rn-1 + An-1*Rn-2 + … + A0*R0
R0的值为1, 因此也可以写为
y = An-1*Rn-1 + An-1*Rn-2 + … + A0 (公式1)

10进制转任意进制

公式1可以变形为
y = A0 + R * W, 其中 W = An-1*Rn-2 + … +A
A0y/R的余数
W 为y/R的商
然后对W执行相同的过程, 分别得到A1, A2, … , An-1

JAVA实现代码

以下是10进制与62进制的互转方式, 62进制用0-9a-zA-Z中的字符表示

 	public static String radix10To62(long num) {
 		if(num<0) {
			throw new IllegalArgumentException("must be non-negative: " + num);
		}
		final int radix = 62;
		char[] outs = new char[64];
		int outsIndex = outs.length;
		long quotient;
		long remainder;
		char c;
		do{
			quotient = num / radix;
			remainder = num % radix;
			if(remainder>=0 && remainder <=9) {
				c = (char) ('0' + remainder);
			}else if(remainder >= 10 && remainder <= (10+26-1)) {
				c = (char) ('a' + (remainder - 10));
			}else {
				c = (char) ('A' + (remainder - 36));
			}
			outs[--outsIndex] = c;
			num = quotient;
		}while(num>0);
		return new String(outs, outsIndex, outs.length - outsIndex);
    	}
	
	public static long radix62To10(String num) {
		int length = num.length();
		long out = 0;
		for(int i=0; i<length; i++) {
			final char c = num.charAt(i);
			int charNum;
			if(c>='0' && c<='9') {
				charNum = c - '0';
			}else if(c>='a' && c <='z') {
				charNum = c - 'a' + 10;
			}else if(c>='A' && c <='Z') {
				charNum = c - 'A' + 10 + 26;
			}else {
				throw new IllegalArgumentException("invalid radix62 char: " + c);
			}
			out = out*62 + charNum;
		}
		return out;
	}

测试

	public static void main(String[] args) throws Exception {
		String radix62 = radix10To62(Long.MAX_VALUE);
		long radix10 = radix62To10(radix62);
		System.out.println(radix62 + ", " + radix10);
	}

打印结果

aZl8N0y58M7, 9223372036854775807

猜你喜欢

转载自blog.csdn.net/wzj_whut/article/details/85225156