Skip to content

Instantly share code, notes, and snippets.

@alkaruno
Created September 9, 2014 14:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alkaruno/b84162bae5115f4ca99b to your computer and use it in GitHub Desktop.
Save alkaruno/b84162bae5115f4ca99b to your computer and use it in GitHub Desktop.
Base64 encode & decode (only for numbers) in JavaScript
var Base64 = (function () {
var ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var Base64 = function () {};
var _encode = function (value) {
if (typeof(value) !== 'number') {
throw 'Value is not number!';
}
var result = '', mod;
do {
mod = value % 64;
result = ALPHA.charAt(mod) + result;
value = Math.floor(value / 64);
} while(value > 0);
return result;
};
var _decode = function (value) {
var result = 0;
for (var i = 0, len = value.length; i < len; i++) {
result *= 64;
result += ALPHA.indexOf(value[i]);
}
return result;
};
Base64.prototype = {
constructor: Base64,
encode: _encode,
decode: _decode
};
return Base64;
})();
@alkaruno
Copy link
Author

alkaruno commented Sep 9, 2014

var base64 = new Base64();
var s = base64.encode(1234567890); // BJlgLS
var n = base64.decode('BJlgLS'); // 1234567890

@StockerMC
Copy link

StockerMC commented Sep 26, 2019

How do we decode based on the specific value encoded by _encode, A.K.A. setting var n = base64.decode(custom result); as a custom result? (I know this is 5 years later)

@denisx
Copy link

denisx commented Apr 28, 2020

the algorithm skip some values :(

@denisx
Copy link

denisx commented May 12, 2020

at dictionary [a-zA-Z0-9_-] (64 symbols)
your variant has
.encode(63) = -,
.encode(64) = ba, must be aa

@TheFanatr
Copy link

The fix is value = ... - 1 and while (value > -1), in encode, and result += Math.pow(64, i) * (ALPHA.indexOf(value[i]) + Math.min(i, 1)) instead of the contents of the for in decode.
.

@kirillgroshkov
Copy link

Using the forementioned fix, this is what I ended up with:

const BASE62 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const BASE64 = BASE62 + '+/'
const BASE64URL = BASE62 + '-_'

export function numberToBase64(n: number): string {
  return numberToBase(n, BASE64)
}

export function numberToBase64url(n: number): string {
  return numberToBase(n, BASE64URL)
}

function numberToBase(n: number, alphabet: string): string {
  const alen = alphabet.length
  let result = ''

  do {
    result = alphabet.charAt(n % alen) + result
    n = Math.floor(n / alen) - 1
  } while(n > -1)

  return result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment