Here you can find the source of base64Encode(byte[] bytes)
Parameter | Description |
---|---|
bytes | Bytes to encode. |
Parameter | Description |
---|---|
IllegalArgumentException | if bytes is null or exceeds 3/4ths of Integer.MAX_VALUE. |
public static String base64Encode(byte[] bytes)
//package com.java2s; //License from project: Apache License public class Main { private static final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; private static final int BASE64_UPPER_BOUND = Integer.MAX_VALUE / 4 * 3; /**/*ww w . j av a 2 s . c o m*/ * Base64 encodes a byte array. * * @param bytes Bytes to encode. * @return Encoded string. * @throws IllegalArgumentException if {@code bytes} is null or exceeds 3/4ths of {@code * Integer.MAX_VALUE}. */ public static String base64Encode(byte[] bytes) { if (bytes == null) { throw new IllegalArgumentException("Input bytes must not be null."); } if (bytes.length >= BASE64_UPPER_BOUND) { throw new IllegalArgumentException("Input bytes length must not exceed " + BASE64_UPPER_BOUND); } // Every three bytes is encoded into four characters. // // Example: // input |0 1 0 1 0 0 1 0|0 1 1 0 1 1 1 1|0 1 1 0 0 0 1 0| // encode grouping |0 1 0 1 0 0|1 0 0 1 1 0|1 1 1 1 0 1|1 0 0 0 1 0| // encoded ascii | U | m | 9 | i | int triples = bytes.length / 3; // If the number of input bytes is not a multiple of three, padding characters will be added. if (bytes.length % 3 != 0) { triples += 1; } // The encoded string will have four characters for every three bytes. char[] encoding = new char[triples << 2]; for (int in = 0, out = 0; in < bytes.length; in += 3, out += 4) { int triple = (bytes[in] & 0xff) << 16; if (in + 1 < bytes.length) { triple |= ((bytes[in + 1] & 0xff) << 8); } if (in + 2 < bytes.length) { triple |= (bytes[in + 2] & 0xff); } encoding[out] = BASE64_CHARS.charAt((triple >> 18) & 0x3f); encoding[out + 1] = BASE64_CHARS.charAt((triple >> 12) & 0x3f); encoding[out + 2] = BASE64_CHARS.charAt((triple >> 6) & 0x3f); encoding[out + 3] = BASE64_CHARS.charAt(triple & 0x3f); } // Add padding characters if needed. for (int i = encoding.length - (triples * 3 - bytes.length); i < encoding.length; i++) { encoding[i] = '='; } return String.valueOf(encoding); } }