Advertisement
Guest User

base64 encoding/decoding without for loop

a guest
Sep 19th, 2014
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. String.prototype.toBase64 = function()
  2. {
  3.     var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
  4.     return this.split("").map(function(q, i, a) { return i % 3 === 0 ? a.slice(i, i + 3) : null; }).filter(function(e) { return e; }).map(function(q)
  5.     {
  6.         var value = q.reduce(function(p, c, i) { return p | (c.charCodeAt(0) << (2 - i) * 8); }, 0) >>> 0;
  7.         return [18, 12, 6, 0].map(function(i) { return alphabet[(value >> i) & 0x3f]; }).join("").substring(0, q.length + 1) + "==".substring(0, 3 - q.length);
  8.     }).join("");
  9. }
  10.  
  11. String.prototype.fromBase64 = function()
  12. {
  13.     var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").reduce(function(p, c, i) { p[c] = i; return p; }, { "=": 0});
  14.     return (this.replace(/\s/gm, "").match(/.{1,4}/g) || []).map(function(q)
  15.     {
  16.         var value = q.split("").reduce(function(p, c, i) { return (p << 6) + alphabet[c]; }, 0) >>> 0;
  17.         return [16, 8, 0].map(function(i) { return String.fromCharCode((value >>> i) & 0xff); }).join("").substr(0, q.split("=")[0].length - 1);
  18.     }).join("");
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement