IPを4ビット暗号化する

2908 ワード

必要に応じて、0〜255のIPを4ビット変換する必要があり、例えば255が「vc 52」のような4文字の文字列に変換される.

public class Base36 {
	private final static int addition = 100000;
	private final static byte[] Base36 = {
			(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
			(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
			(byte) 'A', (byte) 'B',	(byte) 'C', (byte) 'D', (byte) 'E',
			(byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', 
			(byte) 'K', (byte) 'L',	(byte) 'M', (byte) 'N', (byte) 'O',
			(byte) 'P', (byte) 'Q',	(byte) 'R', (byte) 'S', (byte) 'T',
			(byte) 'U', (byte) 'V',	(byte) 'W', (byte) 'X', (byte) 'Y',
			(byte) 'Z'
	};
	private static int transform(int base){
		int level = addition;
		base += level;
		System.out.println(base);
		return base;
	}
	public static String encode(int dex){
		dex = transform(dex);
		StringBuilder code36 = new StringBuilder();
		int quotient = dex;
		int remainder = 0;
		char temp = '0';
		while((quotient / 36) > 0){
			remainder = quotient % 36;
			temp = (char) Base36[remainder];
			code36.append(temp);
			quotient = quotient / 36;
		}
		if((remainder = quotient % 36) > 0){
			code36.append((char) Base36[remainder]);
		}
		return code36.toString();
	}
	
	public static int decode(String code){
		int base = 0;
		int level = 0;
		for(int i = 0; i < code.length(); i++){
			level = getIndex((byte) code.charAt(i));
			if(i == 0){
				base += level;
			} else if(i == 1){
				base += level * 36;
			} else if(i == 2){
				base += level * 36*36;
			} else if(i == 3){
				base += level * 36*36*36;
			}
		}
		System.out.println(base);
		base %= addition;
		return base;
	}
	
	private static int getIndex(byte code){
		code = change2UpCase(code);
		int index = 0;
		for(int i = 0; i < Base36.length; i++){
			if(Base36[i] == code){
				index = i;
				break;
			}
		}
		return index;
	}
	
	private static byte change2UpCase(byte code){
		if(code >= 'a' && code <= 'z'){
			code = (byte) (code - 32);
		}
		return code;
	}
	
	public static void main(String[] args) {
//		String result = encode(255);
//		System.out.println(result);
		System.out.println(decode("vC52"));
	}
}