javascript to binary method code example
Example 1: number to binary javascript
const convertNumberToBinary = n => {
let binary = (n >>> 0).toString(2).split('').sort().join('');
let number = parseInt(binary, 2);
return number;
}
Example 2: DECIMAL TO BINARY CONVERSION javascript
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}`);
}
let number = prompt('Enter a decimal number: ');
convertToBinary(number);