Java tutorial
//package com.java2s; /* * Copyright 2004-2014 the Seasar Foundation and the Others. * * 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 PAD = '='; private static final byte[] DECODE_TABLE = new byte[128]; public static byte[] decodeAsBase64(final String inData) { int num = (inData.length() / 4) - 1; int lastBytes = getLastBytes(inData); byte[] outData = new byte[num * 3 + lastBytes]; for (int i = 0; i < num; i++) { decode(inData, i * 4, outData, i * 3); } switch (lastBytes) { case 1: decode1byte(inData, num * 4, outData, num * 3); break; case 2: decode2byte(inData, num * 4, outData, num * 3); break; default: decode(inData, num * 4, outData, num * 3); } return outData; } private static int getLastBytes(final String inData) { int len = inData.length(); if (inData.charAt(len - 2) == PAD) { return 1; } else if (inData.charAt(len - 1) == PAD) { return 2; } else { return 3; } } private static void decode(final String inData, final int inIndex, final byte[] outData, final int outIndex) { byte b0 = DECODE_TABLE[inData.charAt(inIndex)]; byte b1 = DECODE_TABLE[inData.charAt(inIndex + 1)]; byte b2 = DECODE_TABLE[inData.charAt(inIndex + 2)]; byte b3 = DECODE_TABLE[inData.charAt(inIndex + 3)]; outData[outIndex] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); outData[outIndex + 1] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); outData[outIndex + 2] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f); } private static void decode1byte(final String inData, final int inIndex, final byte[] outData, final int outIndex) { byte b0 = DECODE_TABLE[inData.charAt(inIndex)]; byte b1 = DECODE_TABLE[inData.charAt(inIndex + 1)]; outData[outIndex] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); } private static void decode2byte(final String inData, final int inIndex, final byte[] outData, final int outIndex) { byte b0 = DECODE_TABLE[inData.charAt(inIndex)]; byte b1 = DECODE_TABLE[inData.charAt(inIndex + 1)]; byte b2 = DECODE_TABLE[inData.charAt(inIndex + 2)]; outData[outIndex] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); outData[outIndex + 1] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); } }