Java – Base64 Encode (Mã hóa base64)

how to encode a byte array to base64 in java?


<pre>private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        .toCharArray();

/**
 * @param data
 * @return
 */
public String encode(byte[] data) {
    int start = 0;
    int len = data.length;
    StringBuffer buf = new StringBuffer(data.length * 3 / 2);

    int end = len - 3;
    int i = start;
    int n = 0;

    while (i <= end) {
        int d = ((((int) data[i]) & 0x0ff) << 16)
                | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff); buf.append(legalChars[(d >> 18) & 63]);
        buf.append(legalChars[(d >> 12) & 63]);
        buf.append(legalChars[(d >> 6) & 63]);
        buf.append(legalChars[d & 63]);

        i += 3;

        if (n++ >= 14) {
            n = 0;
            buf.append(" ");
        }
    }

    if (i == start + len - 2) {
        int d = ((((int) data[i]) & 0x0ff) << 16)
                | ((((int) data[i + 1]) & 255) << 8); buf.append(legalChars[(d >> 18) & 63]);
        buf.append(legalChars[(d >> 12) & 63]);
        buf.append(legalChars[(d >> 6) & 63]);
        buf.append("=");
    } else if (i == start + len - 1) {
        int d = (((int) data[i]) & 0x0ff) << 16; buf.append(legalChars[(d >> 18) & 63]);
        buf.append(legalChars[(d >> 12) & 63]);
        buf.append("==");
    }

    return buf.toString();
}</pre>

Advertisements

One thought on “Java – Base64 Encode (Mã hóa base64)

  1. Pingback: Java | [ David Ng ]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s