Skip to content

Instantly share code, notes, and snippets.

@ollie314
Last active August 27, 2015 08:54
Show Gist options
  • Select an option

  • Save ollie314/945960705693f0c8053d to your computer and use it in GitHub Desktop.

Select an option

Save ollie314/945960705693f0c8053d to your computer and use it in GitHub Desktop.
Simple base convertion in javascript

Base convertion sample (javascript)

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
@ollie314
Copy link
Copy Markdown
Author

intersting way to generate a h2b <-> b2h translation vector :

var b2h = [];
var h2b = {};
for (var i = 0; i < 256; i++) {
   b2h[i] = (i + 0x100).toString(16).substr(1);
   h2b[b2h[i]] = i;
}

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