Java Base64 base64(final byte[] stringArray)

Here you can find the source of base64(final byte[] stringArray)

Description

base

License

Open Source License

Declaration

public static String base64(final byte[] stringArray) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

    public static String base64(final byte[] stringArray) {

        final StringBuilder encoded = new StringBuilder();

        // determine how many padding bytes to add to the output
        final int paddingCount = (3 - (stringArray.length % 3)) % 3;
        // add any necessary padding to the input
        final byte[] paddedArray = zeroPad(stringArray.length + paddingCount, stringArray);
        // process 3 bytes at a time, churning out 4 output bytes
        for (int i = 0; i < paddedArray.length; i += 3) {
            final int j = ((paddedArray[i] & 0xff) << 16) + ((paddedArray[i + 1] & 0xff) << 8)
                    + (paddedArray[i + 2] & 0xff);

            encoded.append(BASE64ALPHA.charAt((j >> 18) & 0x3f));
            encoded.append(BASE64ALPHA.charAt((j >> 12) & 0x3f));
            encoded.append(BASE64ALPHA.charAt((j >> 6) & 0x3f));
            encoded.append(BASE64ALPHA.charAt(j & 0x3f));
        }//from   w w  w.j  av  a2s .  co m

        encoded.setLength(encoded.length() - paddingCount);
        return encoded.toString();
    }

    private static byte[] zeroPad(final int length, final byte[] bytes) {
        final byte[] padded = new byte[length];
        System.arraycopy(bytes, 0, padded, 0, bytes.length);
        return padded;
    }
}

Related

  1. base64()
  2. base64(byte[] buf)
  3. base64(byte[] buff)
  4. base64(byte[] data)
  5. base64(byte[] raw)
  6. Base64(String msg)
  7. base64(String string)
  8. base64(String value)
  9. base64Append(StringBuilder sb, int digit, boolean haveNonZero)