Java Base64 Encode toBase64(final byte[] value)

Here you can find the source of toBase64(final byte[] value)

Description

Convert byte array to Base64 string.

License

Open Source License

Parameter

Parameter Description
value Byte array to convert.

Return

Base64 string.

Declaration

public static String toBase64(final byte[] value) 

Method Source Code

//package com.java2s;
// and/or modify it under the terms of the GNU General Public License 

public class Main {
    private static final char[] BASE_64_ARRAY = { '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', '+', '/', '=' };

    /**/*  www. j  av  a 2s  . c  o  m*/
     * Convert byte array to Base64 string.
     * 
     * @param value
     *            Byte array to convert.
     * @return Base64 string.
     */
    public static String toBase64(final byte[] value) {
        StringBuilder str = new StringBuilder((value.length * 4) / 3);
        int b;
        for (int pos = 0; pos < value.length; pos += 3) {
            b = (value[pos] & 0xFC) >> 2;
            str.append(BASE_64_ARRAY[b]);
            b = (value[pos] & 0x03) << 4;
            if (pos + 1 < value.length) {
                b |= (value[pos + 1] & 0xF0) >> 4;
                str.append(BASE_64_ARRAY[b]);
                b = (value[pos + 1] & 0x0F) << 2;
                if (pos + 2 < value.length) {
                    b |= (value[pos + 2] & 0xC0) >> 6;
                    str.append(BASE_64_ARRAY[b]);
                    b = value[pos + 2] & 0x3F;
                    str.append(BASE_64_ARRAY[b]);
                } else {
                    str.append(BASE_64_ARRAY[b]);
                    str.append('=');
                }
            } else {
                str.append(BASE_64_ARRAY[b]);
                str.append("==");
            }
        }

        return str.toString();
    }
}

Related

  1. toBase64(byte[] aValue)
  2. toBase64(byte[] buf, int start, int length)
  3. toBase64(byte[] data)
  4. toBase64(byte[] data)
  5. toBase64(final byte[] bytes)
  6. toBase64(final String str)
  7. toBase64(int x)
  8. toBase64(long num)
  9. toBase64(long value)