携程-Base64编码算法-java

2017-09-21  本文已影响0人  Jacinth
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

上一篇下一篇

猜你喜欢

热点阅读