Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class Base64 {
- public static void main(String[] args) {
- byte[] bytes = "ABCDEFG".getBytes();
- String encoded = encode(bytes);
- if (encoded.equals("QUJDREVGRw==") == false) {
- throw new AssertionError(encoded);
- }
- byte[] decoded = decode(encoded);
- if (Arrays.equals(decoded, bytes) == false) {
- throw new AssertionError(new String(decoded));
- }
- }
- private static final char[] CONVERSION_TABLE =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
- .toCharArray();
- public static String encode(byte[] bs) {
- int l = bs.length;
- int q = l / 3;
- int m = l % 3;
- char[] cs = new char[(q + (m == 0 ? 0 : 1)) * 4];
- int index = 0;
- for (int i = 0; i < q; i++) {
- int a = bs[i * 3] << 16 | bs[i * 3 + 1] << 8 | bs[i * 3 + 2];
- cs[index++] = CONVERSION_TABLE[a >> 18 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a >> 12 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a >> 6 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a & 0x3f];
- }
- if (m == 2) {
- int a = bs[l - 2] << 8 | bs[l - 1];
- cs[index++] = CONVERSION_TABLE[a >> 10 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a >> 4 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a << 2 & 0x3f];
- } else if (m == 1) {
- int a = bs[l - 1];
- cs[index++] = CONVERSION_TABLE[a >> 2 & 0x3f];
- cs[index++] = CONVERSION_TABLE[a << 4 & 0x3f];
- }
- while (index < cs.length) {
- cs[index++] = '=';
- }
- return String.valueOf(cs);
- }
- public static byte[] decode(String text) {
- char[] cs = text.toCharArray();
- int q = cs.length / 4;
- byte[] bs = new byte[q * 3];
- int index = 0;
- for (int i = 0; i < q; i++) {
- int a =
- indexOf(cs[i * 4]) << 18
- | indexOf(cs[i * 4 + 1]) << 12
- | indexOf(cs[i * 4 + 2]) << 6
- | indexOf(cs[i * 4 + 3]);
- bs[index++] = (byte) (a >> 16);
- bs[index++] = (byte) (a >> 8);
- bs[index++] = (byte) a;
- }
- while (bs[--index] == 0) {
- }
- return Arrays.copyOf(bs, index + 1);
- }
- private static int indexOf(char c) {
- if (c == '+') {
- return 62;
- } else if (c == '/') {
- return 63;
- } else if ('A' <= c && c <= 'Z') {
- return c - 65;
- } else if ('a' <= c && c <= 'z') {
- return c - 71;
- } else if ('0' <= c && c <= '9') {
- return c + 4;
- }
- return 0;
- }
- }
Add Comment
Please, Sign In to add comment