// Based on public domain code by Tyler Akins <http://rumkin.com/>
// Original code at http://rumkin.com/tools/compression/base64.php
var Base64 = (function() {
function encode_base64(data) {
var out = "", c1, c2, c3, e1, e2, e3, e4;
for (var i = 0; i < data.length; ) {
c1 = data.charCodeAt(i++);
c2 = data.charCodeAt(i++);
c3 = data.charCodeAt(i++);
e1 = c1 >> 2;
e2 = ((c1 & 3) << 4) + (c2 >> 4);
e3 = ((c2 & 15) << 2) + (c3 >> 6);
e4 = c3 & 63;
if (isNaN(c2))
e3 = e4 = 64;
else if (isNaN(c3))
e4 = 64;
out += tab.charAt(e1) + tab.charAt(e2) + tab.charAt(e3) + tab.charAt(e4);
}
return out;
}
function decode_base64(data) {
var out = "", c1, c2, c3, e1, e2, e3, e4;
for (var i = 0; i < data.length; ) {
e1 = tab.indexOf(data.charAt(i++));
e2 = tab.indexOf(data.charAt(i++));
e3 = tab.indexOf(data.charAt(i++));
e4 = tab.indexOf(data.charAt(i++));
c1 = (e1 << 2) + (e2 >> 4);
c2 = ((e2 & 15) << 4) + (e3 >> 2);
c3 = ((e3 & 3) << 6) + e4;
out += String.fromCharCode(c1);
if (e3 != 64)
out += String.fromCharCode(c2);
if (e4 != 64)
out += String.fromCharCode(c3);
}
return out;
}
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return { encode:encode_base64, decode:decode_base64 };
})();
Webby thoughts, most about around interesting applications of ecmascript in relation to other open web standards. I live in Mountain View, California, and spend some of my spare time co-maintaining Greasemonkey together with Anthony Lieuallen.
2007-11-01
Javascript Base64 singleton
Similar to the javascript MD5 singleton micro-lib I wrapped up some time ago (source code), here is an even tinier Base64.encode / Base64.decode singleton (source code) I reworked from Tyler Akins' public domain original. Absolutely no error handling or recovery in this variant, so don't pass anything but eight-bit data to Base64.encode, nor correct base64 data to Base64.decode.
2 comments:
Limited HTML (such as <b>, <i>, <a>) is supported. (All comments are moderated by me amd rel=nofollow gets added to links -- to deter and weed out monetized spam.)
I would prefer not to have to do this as much as you do. Comments straying too far off the post topic often lost due to attention dilution.
Note: Only a member of this blog may post a comment.
It is worth pointing out, that if you run javascript in a browser context, you don't need this overkill to encode and decode Base64 -- Base64.encode is called window.btoa and Base64.decode is called window.btoa, and your browser's native implementation is a lot faster, too.
ReplyDelete>> your browser's native implementation is a lot faster, too
ReplyDeleteassuming your browser provides that function. This is absent on IE6, IE7 & IE8 (as of beta1). It's also worth noting this isn't part of any standard.