Base Conversion

by justjohn

JavaScript

String.prototype.repeat = function (times){
    return new Array(times + 1).join(this);
};

String.prototype.pad = function (length, str, direction){
    if (this.length >= length) return this;
    
    var pad = (str == null ? ' ' : '' + str)
    .repeat(length - this.length)
    .substr(0, length - this.length);
    
    if (!direction || direction == 'right') return this + pad;
    if (direction == 'left') return pad + this;
    
    return pad.substr(0, (pad.length / 2).floor()) + this + pad.substr(0, (pad.length / 2).ceil());
};

function toBase(str, base, blockLen)
{
    var len = blockLen || 7;
    var base = base || 2;
    var output = "";
    
    for (var i=0; i<str.length; i++) {
        var chr = str.charCodeAt(i);
        var binary = chr.toString(base);
        if (binary.length < len) binary = "0" + binary;
        
        // console.log(binary);
        output += binary;
    }
    
    return output;
}

function fromBase(input, base, blockLen)
{
    var len = blockLen || 7;
    var base = base || 2;
    var output = "";
    
    if (input.length % len > 0) {
        var rem = len - input.length % len;
        input = input.pad(input.length + rem, "0", 'left')
    }
    
    while (input.length > 0) {
        var chunk = input.substr(0, len);
        // console.log(chunk);
        var chr = parseInt(chunk, base);
        input = input.substring(len);
        output += String.fromCharCode(chr);
    }
    
    return output;
}

var list = "async:lexicon,w:weather:script,w:weather:styles,w:topresults:script,w:topresults:styles";
var binary = toBase(list);

var reverse = fromBase(binary, 2, 8);

console.log(binary);
console.log(reverse);
console.log(list);