Here you can find the source of toBase64(final byte[] bytes)
Parameter | Description |
---|---|
bytes | The bytes to convert. |
public static String toBase64(final byte[] bytes)
//package com.java2s; /*// w ww .ja v a 2 s. c o m * #%L * IOUtils.java - mongodb-async-driver - Allanbank Consulting, Inc. * %% * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public class Main { /** Base64 encoding array according to RFC 2045. */ private static final char[] BASE_64_CHARS = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789+/").toCharArray(); /** * Converts the byte array into a Base64 (RFC 2045) string. * * @param bytes * The bytes to convert. * @return The string version. */ public static String toBase64(final byte[] bytes) { final int length = bytes.length; // Create a buffer with the maximum possible length. final StringBuffer result = new StringBuffer(4 * ((length + 2) / 3)); // Handle each 3 byte group. int index = 0; final int numGroups = length / 3; for (int i = 0; i < numGroups; i++) { final int byte0 = bytes[index++] & 0xff; final int byte1 = bytes[index++] & 0xff; final int byte2 = bytes[index++] & 0xff; result.append(BASE_64_CHARS[byte0 >> 2]); result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f) | (byte1 >> 4)]); result.append(BASE_64_CHARS[((byte1 << 2) & 0x3f) | (byte2 >> 6)]); result.append(BASE_64_CHARS[byte2 & 0x3f]); } // Partial group with padding. final int numBytesInLastGroup = length - (3 * numGroups); if (numBytesInLastGroup > 0) { final int byte0 = bytes[index++] & 0xff; result.append(BASE_64_CHARS[byte0 >> 2]); if (numBytesInLastGroup == 1) { result.append(BASE_64_CHARS[(byte0 << 4) & 0x3f]); result.append("=="); } else { final int byte1 = bytes[index++] & 0xff; result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f) | (byte1 >> 4)]); result.append(BASE_64_CHARS[(byte1 << 2) & 0x3f]); result.append('='); } } return result.toString(); } }