URL短縮符号化、10ビットと64ビットの変換

2411 ワード


package com.yuxd._10to64;

public class Encode10 {
	// 64 
	public static String encode(long origin){
		int position=0;
		String ret="";
		String binary=Long.toBinaryString(origin);
		System.out.println(Long.parseLong(binary, 2));
		position=binary.length()-1;
		while(position>=0){
			String subString=binary.substring((position-5>0?position-5:0), position+1);
			long tempValue=Long.parseLong(subString, 2);
			ret=Character.toString(code[(int)tempValue])+ret;
			position=position-6;
		}
		return ret;
	}
	//64 10 
	public static long decode(String origin){
		int stringPosition=0;
		Long ret=0L;
		while(stringPosition<origin.length()){
			for(int i=0;i<code.length;i++){
				if(origin.charAt(stringPosition)==code[i]){
					ret=ret+pow(64,origin.length()-stringPosition-1)*i;
				}
			}
			stringPosition+=1;
		}
		return ret;
	}
	
	// math pow , math double, , 
	public static long pow(int x,int y){
		long result=1;
		while(y>0){
			result*=x;
			y--;
		}
		return result;
	}
	private static final char[] code={'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','+','-',
									'1','2','3','4','5','6','7','8','9','0'
									};
	/*
	 *  
	 * */
	public static void main(String[] args){
		System.out.println(encode(9223372031234123L));
		System.out.println(decode(encode(92233720361234123L)));
	}
	
}