Skip to content

Instantly share code, notes, and snippets.

@sempostma
Last active December 3, 2018 22:11
Show Gist options
  • Save sempostma/5ab5e324498e41d30d5039cdaeea6cef to your computer and use it in GitHub Desktop.
Save sempostma/5ab5e324498e41d30d5039cdaeea6cef to your computer and use it in GitHub Desktop.
Number to UTF8 and back
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