1function dec2bin(dec){
2 return (dec >>> 0).toString(2);
3}
4
5dec2bin(1); // 1
6dec2bin(-1); // 11111111111111111111111111111111
7dec2bin(256); // 100000000
8dec2bin(-256); // 11111111111111111111111100000000
1const convertNumberToBinary = number => {
2 return (number >>> 0).toString(2);
3}
4
1// program to convert decimal to binary
2function convertToBinary(x) {
3 let bin = 0;
4 let rem, i = 1, step = 1;
5 while (x != 0) {
6 rem = x % 2;
7 console.log(
8 `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}`
9 );
10 x = parseInt(x / 2);
11 bin = bin + rem * i;
12 i = i * 10;
13 }
14 console.log(`Binary: ${bin}`);
15}
16
17// take input
18let number = prompt('Enter a decimal number: ');
19
20convertToBinary(number);
1// Javascript convert a number to a binary equivalent.
2// Syntax: n.toString(radix)
3// Note that radix in this syntax is the radix n will become.
4let n = 100;
5let binary = n.toString(2);
6// => 1100100
7
8// Convert a binary number to a radix of 10 equivalent.
9// Syntax: parseInt(num, radix).
10// Note that radix in this syntax is denoting i's current radix.
11let i = 1100100;
12let number = parseInt(i, 2);
13// => 100
1/* From decimal to binary (similar fo rother base) */
2const num = 7;
3num.toString(2); // output: "111"
4
5/* From binary (similar fo rother base) to decimal */
6parseInt("111", 2); // output: 7