Java Base64 Encode base64Encode(byte[] buf)

Here you can find the source of base64Encode(byte[] buf)

Description

Traduce un Arreglo de bytes a un String en Base64

License

Apache License

Parameter

Parameter Description
buf el arreglo de bytes (not null)

Return

el String en Base64 (not null)

Declaration

public static String base64Encode(byte[] buf) 

Method Source Code

//package com.java2s;
/*//ww w .  j  a  v  a2 s  . c  o m
 * Copyright 2012 GBSYS.
 *
 * 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.
 */

public class Main {
    private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();

    /**
     * Traduce un Arreglo de bytes a un String en Base64
     *
     * @param buf el arreglo de bytes  (not null)
     * @return el String en Base64 (not null)
     */
    public static String base64Encode(byte[] buf) {
        int size = buf.length;
        char[] ar = new char[((size + 2) / 3) * 4];
        int a = 0;
        int i = 0;
        while (i < size) {
            byte b0 = buf[i++];
            byte b1 = (i < size) ? buf[i++] : 0;
            byte b2 = (i < size) ? buf[i++] : 0;

            int mask = 0x3F;
            ar[a++] = ALPHABET[(b0 >> 2) & mask];
            ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
            ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
            ar[a++] = ALPHABET[b2 & mask];
        }
        switch (size % 3) {
        case 1:
            ar[--a] = '=';
        case 2:
            ar[--a] = '=';
        }
        return new String(ar);
    }
}

Related

  1. base64Encode(byte[] aData)
  2. base64Encode(byte[] aData)
  3. base64Encode(byte[] buf, int tw)
  4. base64Encode(byte[] bytes)
  5. base64encode(byte[] bytes)
  6. base64Encode(byte[] bytes)