Algorithm


  1. Input: Take a decimal number as input.

  2. Initialize variables:

    • Set an empty string or array to store the binary digits.
    • Initialize a variable to store the remainder.
  3. Conversion loop:

    • Use a loop to repeatedly divide the decimal number by 2.
    • At each step, store the remainder as a binary digit (0 or 1).
    • Update the decimal number to be the quotient of the division.
  4. Termination condition:

    • Continue the loop until the decimal number becomes 0.
  5. Output:

    • The binary representation is the sequence of binary digits obtained in reverse order.

 

Code Examples

#1 Code Example- Convert Decimal to Binary

Code - Javascript Programming

// 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);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Step 1: 9/2, Remainder = 1, Quotient = 4
Step 2: 4/2, Remainder = 0, Quotient = 2
Step 3: 2/2, Remainder = 0, Quotient = 1
Step 4: 1/2, Remainder = 1, Quotient = 0
Binary: 1001

#2 Code Example- Convert Decimal to Binary Using toString()

Code - Javascript Programming

// program to convert decimal to binary

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

// convert to binary
const result = number.toString(2);

console.log('Binary:' + ' ' + result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a decimal number: 9
Binary: 1001
Advertisements

Demonstration


JavaScript Programing Example to Convert Decimal to Binary-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way