How to use JS to convert a number to Binary

Our computers understand instructions differently than we do. We use code to program our devices to do certain things, but under the hood, these instructions are encoded into 0s and 1s. In this article, I'll show you how to convert a number to binary using some math, and then show you how to code this using JavaScript.

How to change a number to Binary

To convert a number to binary, we follow these steps

  1. Divide the number by 2
  2. Record the quotient
  3. Record the remainder (It will either be one or zero)
  4. Divide the quotient by 2
  5. Record the new remainder
  6. Repeat step 4 and 5 until you get a quotient that's less than 0. If it's less than 0, record the remainder as 1
  7. Write down all the remainders in order from the newest calculated remainder to the oldest

Let's break this down visually.

Let's say we have the number 35. Dividing this by 2 would give us the following

EquationQuotientRemainder
35 / 2171

That's the first 3 steps. Let's keep going until we reach step 6.

EquationQuotientRemainder
17 / 281
8 / 240
4 / 220
2 / 210
1 / 20 (technically 0.5, but this number is less than 1)1

Now it's time for step 7. Write down all the remainders from the bottom of the table to the top. Our result is 100011 which is the binary of 35!

Coding Solution using JavaScript

We first want to create a function. Let's call it getBinary. This function will also take one value as a parameter:

function getBinary(num){

}

Since we know that we need to record the remainders, let's start with that:

function getBinary(num){
    let number  = num;
    let binary = (number % 2).toString();
}

If you look at our tables above, you'll see that we have to keep dividing the quotient by 2 until we get to a number below 1:

function getBinary(num){
    let number  = num;
    let binary = (number % 2).toString();

    //while loop until we get to a quotient that's below 1
    while (number > 1){  
        // keep dividing the number by 2.  We use parseInt() so that we always get an integer
        number = parseInt (number / 2);  
}

Our final step is to "append" every single remainder together to get our binary number. Let's call the function as well:

function getBinary(num){
    let number  = num;
    // this gets our first remainder
    let binary = (number % 2).toString();

    //while loop until we get to a quotient that's below 1
    while (number > 1){  
        // keep dividing the number by 2.  We use parseInt() so that we always get an integer
        number = parseInt (number / 2);  
        // every time we run a loop, get a new remainder and append it to the old remainder
        binary = (number % 2) + (binary);
    }
    return binary;
}

getBinary(35);

Output:

10011

Happy Coding!