Base64编码转换 java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35558510/article/details/81591868

Base64编码转换问题

Base64编码转换,实现将二进制字节数据编码转换为Base64的字符串数据,以及
将Base64字符串转换回二进制字节数据。
#代码

public class Base64 {
	static char[] table= {'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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
	static int[] revTable= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,0,0,0,0,0};
	public static String encode(byte[] binaryData) {
		StringBuffer codes = new StringBuffer();
		int len = binaryData.length;
		for(int i=0;i<len;i+=3) {
			int data=((((0|(len-i>0?binaryData[i]:0)&0xff)<<8)|(len-i-1>0?binaryData[i+1]:0)&0xff)<<8)|(len-i-2>0?binaryData[i+2]:0)&0xff;
			for(int j=18;j>=0;j-=6)
				codes.append(table[(byte)((data>>j)&0x3f)]);
		}
		if(len%3>0) {
			codes.setCharAt(codes.length()-1, '=');
		}
		if(len%3==1) {
			codes.setCharAt(codes.length()-2, '=');
		}
		return codes.toString();
	}

	public static byte[] decode(String s) {
		int len = s.length();
		byte[] codes = new byte[len*3/4-(s.charAt(len-1)=='='?1:0)-(s.charAt(len-2)=='='?1:0)];	
		int buffer=0,bufferLen=0,p=0;
		for(int i=0;i<codes.length;i++) {
			while(bufferLen<8) {
				if(bufferLen==0) buffer=0;
				buffer=(buffer<<6)|(revTable[(int)s.charAt(p++)]&0x3f);
				bufferLen+=6;
			}
			codes[i]=(byte) ((buffer>>(bufferLen-8))&0xff);
			bufferLen-=8;
		}
		return codes;
	}

	public static void main(String[] args) {
		byte[] a = { 1, 2, 3, -7, -9, 110};
		String s = encode(a);
		System.out.println(s);
		byte[] b = decode(s);

		for (int i = 0; i < b.length; i++) {
			System.out.print(b[i] + " ");
		}
		System.out.println();

	}

}

猜你喜欢

转载自blog.csdn.net/qq_35558510/article/details/81591868