Javascript Function to Convert from Binary to Decimal

2013-04-18 17:07:01

Supports negative numbers!


function binaryStringToDecimal(binaryString) {

    var out = 0, bit,
        isNeg = binaryString.substring(0, 1) == '-',
        len = binaryString.length;

    for(var i = isNeg ? 1 : 0; i < len; i++) {

        bit = binaryString.substring(i, i+1);

        if(bit == '0') { continue }

        out += Math.pow(2, len-i-1);

    }

    return out*(isNeg ? -1 : 1);

}

>> convert from decimal to binary