Skip to content

Instantly share code, notes, and snippets.

@Downchuck
Created November 4, 2011 07:41
Show Gist options
  • Save Downchuck/1338858 to your computer and use it in GitHub Desktop.
Save Downchuck/1338858 to your computer and use it in GitHub Desktop.
base64 decoder for typed arrays
function(
d, // base64 data (in IE7 or older, use .split('') to get this working
b, // replacement map ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
h, // typed array subarray method (.subarray || .subset || .slice)
g, // result buffer
c, // character and - ascii value buffer
u, // bit storage
r, // result byte counter
q, // bit counter
x // char counter
){
// buffer and character map, not assuming well-formed input.
g=new Uint8Array(d.length);
h=g.subarray||g.subset||g.slice;
b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (
// initialize result and counters
r = 0, q = x = '';
// get next character
c = d[x++];
// character found in table? initialize bit storage and add its ascii value;
~c && (u = q%4 ? u*64+c : c,
// and if not first of each 4 characters, convert the first 8bits to one ascii character
q++ % 4) ? r += String.fromCharCode(255&u>>(-2*q&6)) : 0
)
// try to find character in table (0-63, not found => -1)
c = b.indexOf(c);
// return result
return r
}
function(d,b,h,g,c,u,r,q,x){g=new Uint8Array(d.length);h=g.subarray||g.subset||g.slice;b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r=0,q=x='';c=d[x++];~c&&(u=q%4?u*64+c:c,q++%4)?g[r++]=(255&u>>(-2*q&6)):0)c=b.indexOf(c);return h.call(g,0,r)};
Copyright* (C) 2011 Charles Pritchard <chuck@jumis.com>
Licensed under the Creative Commons Zero License.
http://creativecommons.org/publicdomain/zero/1.0/
I, Charles Pritchard, hereby release this work into the public domain.
{
"name": "Base64DecoderTypedArray",
"description": "Base64 decoder producing a Typed Array",
"keywords": [
"base64",
"decode",
"padding",
"rfc2045"
]
}
<!DOCTYPE html>
<title>Base64 decoder to Typed Array</title>
<script type="text/javascript">
(function(){
var f = function(d,b,h,g,c,u,r,q,x){g=new Uint8Array(d.length);h=g.subarray||g.subset||g.slice;b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(r=0,q=x='';c=d[x++];~c&&(u=q%4?u*64+c:c,q++%4)?g[r++]=(255&u>>(-2*q&6)):0)c=b.indexOf(c);return h.call(g,0,r)};
, test = {
"Zg==" : "f"
,"Zm8=" : "fo"
,"Zm9v" : "foo"
,"Zm9vYg==" : "foob"
,"Zm9vYmE=" : "fooba"
,"Zm9vYmFy" : "foobar"
,"MTQwYnl0ZX\n MgcnVsZXMh" : "140bytes rules!"
}
, error = 0;
;
for( i in test ) {
var r = f(i);
if( r != test[i] ) {
error++;
document.writeln( 'Expected &quot;'+test[i]+'&quot; for &quot;'+i+'&quot; but got &quot;'+ r + "&quot;<br>" );
}
}
if( error > 0) {
document.writeln( "<br>"+error+ " tests failed!<br>" );
} else {
document.writeln( "<br>Everything is fine!<br>" );
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment