Skip to content

Instantly share code, notes, and snippets.

@chrdek
Created November 5, 2020 09:23
Show Gist options
  • Save chrdek/b4de0f683fb361fc251cb38fc6bf70a0 to your computer and use it in GitHub Desktop.
Save chrdek/b4de0f683fb361fc251cb38fc6bf70a0 to your computer and use it in GitHub Desktop.
base64 encode, decode
//Extend the String object with toBase64() and fromBase64() functions
//ES6..
String.prototype.toBase64 = function() {
var basechars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return [...this].map(c=>c.charCodeAt()).map(n=> {
return ((+n).toString(2).length < 8) ? "0".repeat(8-(+n).toString(2).length)+(+n).toString(2)
:(+n).toString(2);
}).join("")
.replace(/(\d)(?=(?:\d{6})+$)/g,"$1 ")
.split(" ")
.map(d=>parseInt(d,2))
.map(b=>basechars.charAt(b)).join("");
}
String.prototype.fromBase64 = function() {
var baserange = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var h1, h2, h3, h4, o1, o2, o3, bits, i = 0, bytes = [];
do {
[h1, h2, h3, h4] = [baserange.indexOf(this.charAt(i++)),baserange.indexOf(this.charAt(i++)),
baserange.indexOf(this.charAt(i++)),baserange.indexOf(this.charAt(i++))]
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
[o1, o2, o3] = [shiftOp(bits,16,0xFF), shiftOp(bits,8,0xFF), bits & 0xFF]
bytes.push(o1);bytes.push(o2);bytes.push(o3);
} while (i < this.length);
return bytes.map(d=>String.fromCharCode(d)).join("");
}
const shiftOp = (bit, byvals, rev) => bit >> byvals & rev;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment