From 799e3332557bd773b021c599008dd1f63cd7d312 Mon Sep 17 00:00:00 2001 From: "David A. Madore" Date: Wed, 8 Jan 2014 15:36:37 +0100 Subject: Add a base64 encoder (in order to produce data: URLs). --- org/madore/damlengine/Base64.java | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 org/madore/damlengine/Base64.java (limited to 'org') diff --git a/org/madore/damlengine/Base64.java b/org/madore/damlengine/Base64.java new file mode 100644 index 0000000..a31d363 --- /dev/null +++ b/org/madore/damlengine/Base64.java @@ -0,0 +1,47 @@ +package org.madore.damlengine; + +import java.io.InputStream; +import java.io.IOException; + +public final class Base64 { + + public static final char[] base64Alphabet = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; + + public static String encode(InputStream str) { + byte[] inb = new byte[768]; + char[] outb = new char[1024]; + StringBuffer strbuf = new StringBuffer(); + try { + int len; + while ( ( len = str.read(inb) ) > 0 ) { + for ( int i=0 ; 3*i>>2)&0x3f]; + if ( 3*i+1 < len ) + outb[4*i+1] = base64Alphabet[(inb[3*i]&3)<<4 | ((inb[3*i+1]>>>4)&0xf)]; + else + outb[4*i+1] = base64Alphabet[(inb[3*i]&3)<<4]; + if ( 3*i+2 < len ) + outb[4*i+2] = base64Alphabet[(inb[3*i+1]&0xf)<<2 | ((inb[3*i+2]>>>6)&0x3)]; + else if ( 3*i+1 < len ) + outb[4*i+2] = base64Alphabet[(inb[3*i+1]&0xf)<<2]; + else + outb[4*i+2] = '='; + if ( 3*i+2 < len ) + outb[4*i+3] = base64Alphabet[(inb[3*i+2]&0x3f)]; + else + outb[4*i+3] = '='; + } + strbuf.append(outb, 0, ((len+2)/3)*4); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return new String(strbuf); + } + +} -- cgit v1.2.3