初识base64

base64关键代码

 public   String encode(String Data){
              String base64Code = "ABCDEFGHIJKLINOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

            if(Data == null ){      //检测是否为空
                return Data;
            }
            char[] Arr = Data.toCharArray();
            String Strascii = null;
            StringBuilder ascii_all = new StringBuilder();
            for (int i = 0; i  < Arr.length; i++ ){
                Strascii = Integer.toBinaryString ((int)Arr[i]);  //返回Arr数据的二进制
                if(Strascii.length() < 8 ){   //不足八位在高位补0
                    Strascii = "0" + Strascii;
                }
                ascii_all.append(Strascii);
            }
            while (ascii_all.length() % 6 != 0){  //不是6的倍数就要在低位补0
                ascii_all.append("0");
             }
             String Str_ascii_all = ascii_all.toString();
             List List6 = new ArrayList();
             String temp = null;
             while(Str_ascii_all.length()/6 > 0){  //6个一组分成数组
                 temp = Str_ascii_all.substring(0,6);
                 Str_ascii_all = Str_ascii_all.substring(6);
                 List6.add(temp);
             }
             String[] Str6 = List6.toArray(new String[List6.size()]);
             int[] index = new int[Str6.length];
             int overLen = 0;
             if(Data.length()% 3 != 0) {
                 overLen = 3- Data.length()% 3;   //不足3位就在后面加“=”
             }
             //设定存放最终编码的容器
             char[] code = new char[index.length+ overLen];
             for(int i= 0; i< index.length; i++) {
                 //将二进位转换成十进制数字
                 index[i] = Integer.parseInt(Str6[i], 2);  //返回Str6[i]的二进制数

                 code[i] = base64Code.charAt(index[i]);  //按数值索引到对应的字符
             }
             switch(overLen) {
                 case 2:code[code.length- 2] = '=';
                 case 1:code[code.length- 1] = '=';
                 default:
             }
             return String.valueOf(code);
         }

你可能感兴趣的:(初识base64)