Smallest base64 decoder

That I’ve written so far anyway. I’m sure its possible to write a smaller one using perl or maybe even C, but this is the smallest Java decoder I’ve seen.

	private final static char[] base64CharMap =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
		.toCharArray();
	private final static byte[] base64RevCharMap = new byte[256];
	static {
		for (byte i = 0; i < base64CharMap.length; i++)
			base64RevCharMap[base64CharMap[i]] = i;
	}
	/**
	* Decode a base64 encoded data back into a byte array
	* @param text base64 decoded data
	* @return binary
	*/
	public static byte[] base64(String text) {
		if (text == null) return null;
		char[] chars = text.trim().toCharArray();
		int sind = 0, dind = 0, shl = 0;
		byte[] out = new byte[chars.length/4*3];
		while (sind < chars.length && chars[sind+1] != '=') {
			out[dind++] = (byte)
				( (base64RevCharMap[chars[sind++]] << (shl+2))
				| (base64RevCharMap[chars[sind]] >>> (4-shl)));
			if ((shl = (shl + 2) % 6) == 0) sind++;
		}
		return Arrays.copyOf(out, dind);
	}

Now I need to work on my encoder, which is both a mess and way too big, unlike the decoder above which is just a mess 🙂

Update:

Removed wisestring (which was stupid in the first place) in favor of returning a proper byte array. Also cleaned up some syntax.

One Response to “Smallest base64 decoder”

  1. Anatol:

    Thanks for this tool!

Leave a Reply

 

 


Spam prevention powered by Akismet