This is a simple attempt of a base convertion in javascript. This is largely optimizable and this is just a sample.
/**
* This is a factory allow to create a convertion function.
*
* _useString param is optional and by default it is set as false
*
* @param {Number} _original base
* @param {Number} _targetBase the base to convert to
* @param {bool} _useString indicates if we have to return a string (true) or an array (false)
* @return {Function} the converter
*/
function converterFactory(_originalBase, _targetBase, _useString) {
var buffer = [],
useString = _useString || false,
rawBytes = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
orignalBase,
targetBase,
stringify = function () {
var t = buffer;
clear();
if (useString) {
t = t.join('');
}
return t;
},
clear = function () {
buffer = [];
},
convert = function (value) {
var tmp;
if (value) {
tmp = value % targetBase;
buffer.unshift(rawBytes[tmp]);
value = Math.trunc(value / targetBase);
convert(value);
}
},
fromDigit = function(_digits) {
var result, i, digits, base;
base = orignalBase;
if (isFinite(_digits)) {
digits = "" + _digits;
digits = digits.split('');
} else {
digits = _digits;
}
i = result = 0;
for (; i < digits.length; i++) {
result = result * base + rawBytes.indexOf(digits[i]);
}
return result;
};
if(isNaN(_originalBase)) {
throw new Error('Convertion not supported, original base isn\'t a valid number');
}
orignalBase = Number(_originalBase);
if (isNaN(_targetBase) || _targetBase > rawBytes.length) {
// convertion not supported ...
throw new Error('Convertion not supported, base shouldn\'t exceed ' + rawBytes.length);
}
targetBase = Number(_targetBase);
return function (value) {
value = fromDigit(value);
convert(value);
return stringify();
}
}Some exemple of usage.
// create a decimal to bit converter
var d2b = converterFactory(10, 2);
console.log(d2b(1011)); // equivalent d2b('1011');
// -> ["1", "1", "1", "1", "1", "1", "0", "0", "1", "1"]
// create a decimal to hex converter with string output
var d2h = converterFactory(10, 16, true);
console.log(d2h(1011)); // equivalent to d2h('1011');
// -> 3F3
// create an hex to binary converter with string output
var h2b = converterFactory(16, 2, true);
console.log(h2b("AF"));
// -> 10101111
intersting way to generate a h2b <-> b2h translation vector :