Created
September 9, 2014 14:36
-
-
Save alkaruno/b84162bae5115f4ca99b to your computer and use it in GitHub Desktop.
Base64 encode & decode (only for numbers) in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
})(); |
Author
alkaruno
commented
Sep 9, 2014
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)
the algorithm skip some values :(
at dictionary [a-zA-Z0-9_-] (64 symbols)
your variant has
.encode(63) = -
,
.encode(64) = ba
, must be aa
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
.
.
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