Java Base64 Decode base64decode(String string)

Here you can find the source of base64decode(String string)

Description

basedecode

License

Open Source License

Declaration

public static byte[] base64decode(String string) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Main {
    private static final byte[] b64reverseTable = new byte[123];

    public static byte[] base64decode(String string) {
        int len = string.length();
        int iter = len - (len % 4);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int i = 0;
        for (; i < iter; i += 4) {
            byte a = b64reverseTable[string.charAt(i)];
            byte b = b64reverseTable[string.charAt(i + 1)];
            byte c = b64reverseTable[string.charAt(i + 2)];
            byte d = b64reverseTable[string.charAt(i + 3)];

            byte[] bytes = new byte[3];
            bytes[0] = (byte) ((a << 2) ^ ((b & 0b00110000) >>> 4));
            bytes[1] = (byte) (((b & 0b00001111) << 4) ^ ((c & 0b00111100) >>> 2));
            bytes[2] = (byte) (((c & 0b00000011) << 6) ^ d);

            try {
                buffer.write(bytes);//from www. ja va 2s .c o m
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        switch (len - iter) {
        case 0:
            break;
        case 3: {
            byte a = b64reverseTable[string.charAt(i)];
            byte b = b64reverseTable[string.charAt(i + 1)];
            byte c = b64reverseTable[string.charAt(i + 2)];
            byte[] bytes = new byte[2];
            bytes[0] = (byte) ((a << 2) ^ ((b & 0b00110000) >>> 4));
            bytes[1] = (byte) (((b & 0b00001111) << 4) ^ ((c & 0b00111100) >>> 2));
            try {
                buffer.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }

        case 2: {
            byte a = b64reverseTable[string.charAt(i)];
            byte b = b64reverseTable[string.charAt(i + 1)];
            byte[] bytes = new byte[1];
            bytes[0] = (byte) ((a << 2) ^ ((b & 0b00110000) >>> 4));
            try {
                buffer.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
        default:
            throw new RuntimeException("Bad input string format");
        }

        return buffer.toByteArray();
    }
}

Related

  1. base64Decode(String str)
  2. base64Decode(String str)
  3. Base64Decode(String str)
  4. base64decode(String str)
  5. base64Decode(String string)
  6. base64decode(String strMi)
  7. base64decode(String text)
  8. base64decodebyte(String txt)
  9. base64Decoder(char[] src, int start)