Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Last active December 28, 2019 08:48
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 brookjordan/a12b1f270440cf7c489f548c94ca80c4 to your computer and use it in GitHub Desktop.
Save brookjordan/a12b1f270440cf7c489f548c94ca80c4 to your computer and use it in GitHub Desktop.
Convert numbers to base 64
(function() {
const BASE_64_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/'.split('');
Number.prototype._toString = Number.prototype.toString;
window._parseInt = window.parseInt;
Number.prototype.toString = function(base) {
if (base < 37 && base >= 2) {
return Number.prototype._toString.call(this, ...arguments);
}
base = Math.trunc(base);
if (base > 64 || base < 2) {
throw 'Uncaught RangeError: toString() radix argument must be between 2 and 64';
}
let base64Chars = BASE_64_CHARS.slice(0, base);
let rest = Number(this) || 0;
let base64 = '';
while (true) {
rest = Math.floor(rest);
base64 = base64Chars[rest % base] + base64;
if (rest < base) {
break;
} else {
rest = rest /= base;
}
}
return base64;
};
window.parseInt = function(str, base) {
if (base < 37) {
return window._parseInt(...arguments);
}
base = Math.trunc(base);
if (base > 64) {
return NaN;
}
let base64Chars = BASE_64_CHARS.slice(0, base);
let chars = String(str).split('');
let decimal = 0;
for (let [i, char] of Object.entries(chars)) {
let position = base64Chars.indexOf(char);
if (position === -1) { return NaN; }
decimal += position * Math.pow(base, chars.length - Number(i) - 1);
}
return decimal;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment