js num to binary code example

Example 1: javascript convert number to binary

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

dec2bin(1);    // 1
dec2bin(-1);   // 11111111111111111111111111111111
dec2bin(256);  // 100000000
dec2bin(-256); // 11111111111111111111111100000000

Example 2: javascript convert to and from binary

/* From decimal to binary (similar fo rother base) */
const num = 7;
num.toString(2); // output: "111"

/* From binary (similar fo rother base) to decimal */
parseInt("111", 2); // output: 7

Example 3: DECIMAL TO BINARY CONVERSION javascript

// program to convert decimal to binary
function convertToBinary(x) {
    let bin = 0;
    let rem, i = 1, step = 1;
    while (x != 0) {
        rem = x % 2;
        console.log(
            `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}`
        );
        x = parseInt(x / 2);
        bin = bin + rem * i;
        i = i * 10;
    }
    console.log(`Binary: ${bin}`);
}

// take input
let number = prompt('Enter a decimal number: ');

convertToBinary(number);

Example 4: number to binary javascript

// method one
function convertNumberToBinary (num) {
 return parseInt([...num.toString(2)].reverse().join(''), 2);
}

// methode two
function convertNumberToBinary (num) {
 return parseInt(num.toString(2).slice('').reverse().join(''), 2);
}

// methode three
function convertNumberToBinary (num) {
  let binary = (n >>> 0).toString(2).split('').sort().join('');
  let number = parseInt(binary, 2);
  return num;
}