Java Base64 Decode base64decode(String s)

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

Description

basedecode

License

Open Source License

Declaration

public static byte[] base64decode(String s) 

Method Source Code

//package com.java2s;
/*/*from  w ww. jav a  2 s .  com*/
 *  $File$ $Revision$ $Date$
 *
 *  ADOBE SYSTEMS INCORPORATED
 *    Copyright 2007 Adobe Systems Incorporated
 *    All Rights Reserved.
 *
 *  NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the 
 *  terms of the Adobe license agreement accompanying it.  If you have received this file from a 
 *  source other than Adobe, then your use, modification, or distribution of it requires the prior 
 *  written permission of Adobe.
 */

public class Main {
    public static byte[] base64decode(String s) {
        return base64decode(s.getBytes());
    }

    public static byte[] base64decode(byte[] b) {
        if ((b.length % 4) != 0)
            throw new RuntimeException("invalid base64 array: length="
                    + b.length);

        int l = b.length / 4 * 3;

        if (b[b.length - 1] == '=')
            l--;
        if (b[b.length - 2] == '=')
            l--;

        byte[] result = new byte[l];
        int ri = 0;

        for (int i = 0; i < b.length; i += 4) {
            int v = (getBase64(b[i + 0]) << 18)
                    | (getBase64(b[i + 1]) << 12)
                    | (getBase64(b[i + 2]) << 6)
                    | (getBase64(b[i + 3]) << 0);

            result[ri++] = (byte) ((v >> 16) & 0xFF);
            if (ri >= result.length)
                break;

            result[ri++] = (byte) ((v >> 8) & 0xFF);
            if (ri >= result.length)
                break;

            result[ri++] = (byte) ((v >> 0) & 0xFF);
            if (ri >= result.length)
                break;
        }

        return result;
    }

    private static int getBase64(byte c) {
        if (c >= 'A' && c <= 'Z')
            return (int) c - (int) 'A';
        if (c >= 'a' && c <= 'z')
            return (int) c - (int) 'a' + 26;
        if (c >= '0' && c <= '9')
            return (int) c - (int) '0' + 52;
        if (c == '+')
            return 62;
        if (c == '/')
            return 63;

        return 0;
    }
}

Related

  1. base64Decode(String data)
  2. base64Decode(String input)
  3. base64Decode(String s)
  4. base64Decode(String s)
  5. base64Decode(String s)
  6. base64Decode(String str)
  7. base64Decode(String str)
  8. Base64Decode(String str)
  9. base64Decode(String str)