Java Base64 Encode base64Encode(byte[] in)

Here you can find the source of base64Encode(byte[] in)

Description

Encode an array of bytes as a Base64 string

License

Open Source License

Parameter

Parameter Description
data a parameter

Declaration

public static String base64Encode(byte[] in) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w.jav a 2 s.c o  m*/
 * This file is part of MML.
 *
 *  MML is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  MML is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MML.  If not, see <http://www.gnu.org/licenses/>.
 *  (c) copyright Desmond Schmidt 2014
 */

public class Main {
    private static final String codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    /**
     * Encode an array of bytes as a Base64 string
     * @param data
     * @return 
     */
    public static String base64Encode(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();
    }
}

Related

  1. base64encode(byte[] bytes)
  2. base64encode(byte[] data)
  3. base64Encode(byte[] data)
  4. base64Encode(byte[] data)
  5. base64Encode(byte[] in)
  6. base64Encode(byte[] in)
  7. Base64Encode(byte[] input, boolean addLineBreaks)
  8. base64Encode(byte[] param)
  9. base64encode(final byte[] data)