Last active
December 3, 2018 22:11
-
-
Save sempostma/5ab5e324498e41d30d5039cdaeea6cef to your computer and use it in GitHub Desktop.
Number to UTF8 and back
This file contains hidden or 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
function convertBase(value, fromBase) { | |
return value.split('').reverse().reduce(function (carry, digit, index) { | |
const digitVal = digit.charCodeAt(0); | |
if (digitVal >= fromBase) throw new Error('Invalid digit `' + digit + '` for base ' + fromBase + '.'); | |
return carry += digitVal * (Math.pow(fromBase, index)); | |
}, 0); | |
} | |
function encode(value, toBase = 65535 /* safe range */) { | |
var utf8 = value.toString().split('').map(function(x) { | |
return String.fromCharCode(x); | |
}).join(''); | |
var decValue = convertBase(utf8, 10); | |
var newValue = ''; | |
while (decValue > 0) { | |
newValue = String.fromCharCode(decValue % toBase) + newValue; | |
decValue = (decValue - (decValue % toBase)) / toBase; | |
} | |
return newValue || '0'; | |
} | |
function decode(value, fromBase = 65535 /* safe range */) { | |
return convertBase(value, fromBase); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment