Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    private static final char BASE64PAD = '=';
    private static final byte[] DECODETABLE = new byte[128];

    public static byte[] decode(String data) {
        char[] ibuf = new char[4];
        int ibufcnt = 0;
        byte[] obuf = new byte[data.length() / 4 * 3 + 3];
        int obufcnt = 0;
        for (int i = 0; i < data.length(); i++) {
            char ch = data.charAt(i);
            if (ch == BASE64PAD || ch < DECODETABLE.length && DECODETABLE[ch] != Byte.MAX_VALUE) {
                ibuf[ibufcnt++] = ch;
                if (ibufcnt == ibuf.length) {
                    ibufcnt = 0;
                    obufcnt += _decode(ibuf, obuf, obufcnt);
                }
            }
        }
        if (obufcnt == obuf.length)
            return obuf;
        byte[] ret = new byte[obufcnt];
        System.arraycopy(obuf, 0, ret, 0, obufcnt);
        return ret;
    }

    private static int _decode(char[] ibuf, byte[] obuf, int wp) {
        int outlen = 3;
        if (ibuf[3] == BASE64PAD)
            outlen = 2;
        if (ibuf[2] == BASE64PAD)
            outlen = 1;
        int b0 = DECODETABLE[ibuf[0]];
        int b1 = DECODETABLE[ibuf[1]];
        int b2 = DECODETABLE[ibuf[2]];
        int b3 = DECODETABLE[ibuf[3]];
        switch (outlen) {
        case 1:
            obuf[wp] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
            return 1;
        case 2:
            obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
            obuf[wp] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
            return 2;
        case 3:
            obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3);
            obuf[wp++] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
            obuf[wp] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f);
            return 3;
        default:
            throw new RuntimeException("Internal Error");
        }
    }
}