Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Forked from ste-lam/LICENSE.txt
Created November 20, 2012 12:33
Show Gist options
  • Save lancejpollard/4117663 to your computer and use it in GitHub Desktop.
Save lancejpollard/4117663 to your computer and use it in GitHub Desktop.
base64 encoder w/padding

140byt.es - Base64 encoder

A base64encoder with padding, what shall i say more? This version now includes the amazing improvements made by Jonas Magazinius and LeverOne, for more details visit the "sla.ckers"-forum @ http://sla.ckers.org/forum/read.php?24,36342

Example

var 
	sigma ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
,	sample = "140bytes rocks!"
,	encoded = (function(...){...})(sample, sigma);
function(
a, /* input text */
b, /* mapping table */
c, /* working block */
d, /* input char index */
e /* output text */ ){
for(
// initialize char indices
d=e='';
// cast d to int (floor)
// if the next input index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
a[d|0]||(b='=',d%1);
e+=b[ 63 & c >> 8 - d % 1 * 8 ] // "8 - d % 1 * 8" generates the sequence 2, 4, 6, 8 (first value for d is 0.75)
)c = c << 8 | a.charCodeAt( d-=-.75 ); // note: "d -= -3/4" works too
return e
}
function(a,b,c,d,e){for(d=e='';a[d|0]||(b='=',d%1);e+=b[63&c>>8-d%1*8])c=c<<8|a.charCodeAt(d-=-.75);return e}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "Base64Encoder",
"description": "A JavaScript Base64 encoder in 109 Bytes.",
"keywords": ["base64", "encode", "rfc2045", "sla.ckers", "btoa"]
}
<html>
<body>
<script type="text/javascript">
(function(){
var f = function(a,b,c,d,e){for(d=e='';a[d|0]||(b='=',d%1);e+=b[63&c>>8-d%1*8])c=c<<8|a.charCodeAt(d-=-.75);return e}
, test = {
'' : ''
,'AA==' : '\0'
,'AAA=' : '\0\0'
,'AAAA' : '\0\0\0'
,'AAEC' : '\0\1\2'
,"Zg==" : "f"
,"Zm8=" : "fo"
,"Zm9v" : "foo"
,"Zm9vYg==" : "foob"
,"Zm9vYmE=" : "fooba"
,"Zm9vYmFy" : "foobar"
}
, error = 0;
;
for( i in test ) {
var r = f(test[i], "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "=");
if( r != i ) {
error++;
document.writeln( 'Expected &quot;'+i+'&quot; for &quot;'+test[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