Binary to Decimal and Decimal to Binary in JavaScript

Decimal to Binary:

/*
Convert 13 to binary:

Division
by 2	Quotient    Remainder	   Bit #
----------------------------------------
13/2	    6	        1	     0
6/2	    3	        0	     1
3/2	    1	        1	     2
1/2	    0	        1	     3

*/

function dtob(num, output = '') {
    if (num === 0) {
        return output;
    }
    else {
        let rem = num % 2;
        let quotient = Math.floor(num / 2);
        output = rem + output;
        return dtob(quotient, output);
    }
}

console.log(dtob(13)); // 1101

Easy way to convert Decimal to binary is use javascript function .toString()

let n = 13

n.toString(2) // 1101

Binary to Decimal

// (1101)₂ = (1 × 2³) + (1 × 2²) + (0 × 2¹) + (1 × 2⁰) = (13)₁₀

function btod(num) {
    if(!/^[10]+$/.test(num)) return -1 // If number is not binary return -1.
    num = num.toString(); // Converting number to string so that we can iteate on it.
    let result = 0; // to store result
    let reverseNum = [...num].reverse(); // reveseing the number it will help to convert decimal
    reverseNum.map((v, index) => {
        result += v * Math.pow(2, index);
    });
    return result;
}
console.log(btod(1181)); // -1
console.log(btod(1101)); // 13

Easy way to convert binary to Decimal is use javascript method parseInt

parseInt(1101,2) // 13

Leave a Reply