base 64 Encoder for byte array - Android File Input Output

Android examples for File Input Output:Byte Array

Description

base 64 Encoder for byte array

Demo Code


//package com.java2s;

public class Main {

    public static String base64Encoder(byte[] bytes) {

        StringBuilder result = new StringBuilder();
        String base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

        int prevByteBitCount = 0, nextByteBitCount = 6;// 
        int i = 0, n = 0;// in
        int byteCount = 8 * bytes.length;// byteCount
        byte b = 0;

        while (true) {
            /*  */
            if (prevByteBitCount > 0 && nextByteBitCount > 0) {
    /*w  ww  . j  av  a2s  .  c o  m*/
                b = (byte) (((0xff & bytes[i]) << nextByteBitCount) | ((0xff & bytes[i + 1]) >> (8 - nextByteBitCount)));
   
                b = (byte) (b & 0x3f);
                prevByteBitCount = 8 - nextByteBitCount;
                nextByteBitCount = 6 - prevByteBitCount;
            }
            else if (prevByteBitCount == 0) {
                b = (byte) ((0xff & bytes[i]) >> (8 - nextByteBitCount));// 66
                /* 2bit4bit */
                prevByteBitCount = 2;
                nextByteBitCount = 4;
            }
            else if (nextByteBitCount == 0) {
                b = (byte) (0x3f & bytes[i]);// 
                /* 6bit */
                prevByteBitCount = 0;
                nextByteBitCount = 6;

            }
            result.append(base64.charAt(b));
            n += 6;
            i = n / 8;
            int remainBitCount = byteCount - n;
            if (remainBitCount < 6) {
                if (remainBitCount > 0) {
                    b = bytes[bytes.length - 1];
                    b = (byte) (0x3f & (b << (6 - remainBitCount)));
                    result.append(base64.charAt(b));
                }
                break;
            }
        }
        n = byteCount % 3;
        for (i = 0; i < n; i++)
            result.append("=");

        return result.toString();
    }
}

Related Tutorials