Skip to content

Instantly share code, notes, and snippets.

@edalorzo
Created December 13, 2013 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edalorzo/7953021 to your computer and use it in GitHub Desktop.
Save edalorzo/7953021 to your computer and use it in GitHub Desktop.
Base 64 Encoding and Decoding
(function(){
var index = ['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','+','/','='];
var octets = ["","0","00","000","0000","00000","000000","0000000"];
var sixths = ["","00000","0000","000","00","0"];
var paddings = [[],[],[64,64],[],[64]];
function pad(quantums,code){ return quantums.concat(paddings[code.length % 6]); }
function fixed(quantum){ return quantum + sixths[quantum.length % 6]; }
function encode(all, n){ return all + index[n]; }
function decode(c){ return index.indexOf(c); }
function octfill(bin){ return (bin.length > 8 ? octets[16-bin.length] : octets[8-bin.length]) + bin; }
function sixfill(bin){ return octets[6-bin.length] + bin; }
function pack(all,c){ return all + octfill(c.charCodeAt(0).toString(2)); }
function unpack(all,n){ return all + sixfill(n.toString(2)); }
function quantum(code,n,size){ return code.substr(n,size); }
function asBase64(code){
var items = [];
var count = Math.ceil(code.length / 6);
for(var q=0; q < count; q++){
items.push(parseInt(fixed(quantum(code, q*6, 6)),2));
}
return pad(items,code);
}
function asText(code){
var items = [];
var count = Math.floor(code.length / 8);
for(var q=0; q < count; q++){
var bin = quantum(code, q*8, 8);
if(bin.length === 8){
items.push(parseInt(bin,2));
}
}
return items.map(function(n){ return String.fromCharCode(n);}).join('');
}
function toBase64(text){ return text ? asBase64(text.split('').reduce(pack,'')).reduce(encode,'') : ''; }
function fromBase64(text){ return text ? asText(text.replace(/=/g,'').split('').map(decode).reduce(unpack,'')) : ''; }
String.prototype.toBase64 = function(text){ return toBase64(this); };
String.prototype.fromBase64 = function(text){ return fromBase64(this); };
module.exports.toBase64 = toBase64;
module.exports.fromBase64 = fromBase64;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment