美文网首页
携程-Base64编码算法-java

携程-Base64编码算法-java

作者: Jacinth | 来源:发表于2017-09-21 23:34 被阅读0次
    image.png
    package xiecheng;
    
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Base64 {
    
        public static String CODES = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
    
        /*
         * 请完成下面这个函数,实现题目要求的功能 当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^
         * *****************************开始写代码*****************************
         */
        static String encode(byte[] in) {
            StringBuilder out = new StringBuilder((in.length * 4) / 3);
            int b;
            for (int i = 0; i < in.length; i += 3) {
                b = (in[i] & 0xFC) >> 2;
                out.append(CODES.charAt(b));
                b = (in[i] & 0x03) << 4;
                if (i + 1 < in.length) {
                    b |= (in[i + 1] & 0xF0) >> 4;
                    out.append(CODES.charAt(b));
                    b = (in[i + 1] & 0x0F) << 2;
                    if (i + 2 < in.length) {
                        b |= (in[i + 2] & 0xC0) >> 6;
                        out.append(CODES.charAt(b));
                        b = in[i + 2] & 0x3F;
                        out.append(CODES.charAt(b));
                    } else {
                        out.append(CODES.charAt(b));
                        out.append('=');
                    }
                } else {
                    out.append(CODES.charAt(b));
                    out.append("==");
                }
            }
            return out.toString();
    
        }
    
        /****************************** 结束写代码 ******************************/
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String res;
    
            String _source;
            try {
                _source = in.nextLine();
            } catch (Exception e) {
                _source = null;
            }
    
            res = encode(_source.getBytes());
            System.out.println(res);
        }
    }
    

    提交结果:AC
    参考:
    http://www.cnblogs.com/wangshuo1/p/5797864.html

    相关文章

      网友评论

          本文标题:携程-Base64编码算法-java

          本文链接:https://www.haomeiwen.com/subject/ojhxextx.html