Javascript Function to Convert from Decimal to Binary

2013-04-18 17:04:02

Supports negative numbers!


function decimalToBinaryString(decimalNumber) {

    decimalNumber = parseInt(decimalNumber);

    var n = decimalNumber, isNeg = decimalNumber < 0, out = '';

    isNeg && (n = decimalNumber*(-1));

    while(true) {

        n = n/2;
        if(Math.round(n) != n) {
            out = '1' + out
        } else {
            out = '0' + out
        }

        n = Math.floor(n);

        if(n < 1) { break }

    }

    return (isNeg ? '-' : '')+out
}

>> convert from binary to decimal