In this guide we are going to look at how we can convert a decimal number to binary using JavaScript. We will also go the other way and convert a binary to a decimal number.

We will also build our own custom **text to binary converter **that can take text as input and convert it to binary. It can also take binary as input and convert it back to text. Check out the end of this guide for **full source code and a working application**.

If you simply want the code for converting between the two formats then skip this algorithm part.

Before learning how to convert a decimal to binary using JavaScript we have to learn how to do the conversion by hand. Once you know how to convert any decimal to binary then you can write it in any language.

## Decimal to Binary Conversion Algorithm

The algorithm to do the conversion is not too difficult. What we will do is to take a number X and see if it is odd or even. If it is even then we write a 0, if it is odd then we write a 1. Then we are going to take the number and keep dividing it by 2 until we reach 0. Each time we divide the number we look at the answer. If the answer is an odd number then we add a 1, if it is even then we add a 0. You add them from right to left. Meaning, the first division is the least significant number. If you get a decimal number you round it down to the nearest int.

### Example 1

Let us pick a pretty low and easy number for our first example.

Number: 16

**Round 0:** 16 is an even number so we write a 0**Round 1:** 16 / 2 = 8. 8 is an even number so we write a 0.**Round 2:** 2 / 2 = 4. 4 is an even number so we write a 0.**Round 3:** 4 / 2 = 2. 2 is an even number so we write a 0.**Round 4:** 2 / 2 = 1. 1 is an odd number so we write a 1.

The resulting binary number will then be, **10000**. If you plug that into google you will see that it is correct.

### Example 2

Lets do another number that is a bit more difficult than 16.

Number: 72

**Round 0:** 72 is an even number so we write a 0**Round 1:** 72 / 2 = 36. 36 is an even number so we write a 0**Round 2:** 36 / 2 = 18. 18 is an even number is even so we write a 0.**Round 3:** 18 / 2 = 9. 9 is an odd number so we write a 1.**Round 4:** 9 / 2 = 4.5 = 4. 4 is an even number so we write a 0.**Round 5:** 4 / 2 = 2. 2 is an even number so we write a 0.**Round 5:** 2 / 2 = 1. 1 is an odd number so we write a 1.

The resulting binary number is then: **1001000**.

You can perhaps see from the examples that we will be using a while loop when using JavaScript to convert from decimal to binary. Also, since we round down to the nearest integer when we get a decimal number we will be using integer division to chop off the decimal values.

### Example 3

Lets do one more example before we write code to convert a decimal to binary with JavaScript.

Number: 103

**Round 0:** 103 is an odd number so we write a 1.**Round 1:** 103 / 2 = 51.5 = 51. 51 is an odd number so we write a 1.**Round 2:** 51 / 2 = 25.5 = 25. 25 is an odd number so we write a 1.**Round 3:** 25 / 2 = 12.5 = 12. 12 is an even number so we write a 0.**Round 4:** 12 / 2 = 6. 6 is an even number so we write a 0.**Round 5:** 6 / 2 = 3. 3 is an odd number so we write a 1.**Round 6:** 3 / 2 = 1.5 = 1. 1 is an odd number so we write a 1.

The next number would be 0 so we can stop here. The resulting binary number is: **1100111**.

Now that we know how to convert a decimal number to binary format we can write code in JavaScript.

We will write a function that takes an integer as input and returns the binary number as a string. We will use a loop and keep dividing by 2 until the resulting number is 0. We will use the modulus operator to check if the number is even or odd. Based on the result we will add a 1 or a 0 to the front of the string. Remember that we want to add the existing string onto the new character because it works in reverse, as you can see in the examples. The last number that you divide will be the first number in the binary version. To simulate integer division in JavaScript we will use Math.floor(), which will round it down to the nearest integer for us.

## Decimal to Binary in JavaScript Code

var number = 72; function convertDecimalToBinary(number){ var binary = ""; var temp = number; while(temp > 0){ if(temp % 2 == 0){ binary = "0" + binary; } else { binary = "1" + binary; } temp = Math.floor(temp / 2); } return binary; } console.log(convertDecimalToBinary(number));

You can copy the code to the console in Chrome and try it out. You should see the following results.

**An important note** about the example above is that often you want to pad the binary number to be a certain size. The reason is that you have to know the size of each value when you convert back to decimal. The reason is when you loop over the binary data you have to know how many bits to grab at a time. It is common to use a byte as a size, but it is also possible that things are of difference sizes. You can define your own custom protocol, but for this example we are just going to have all the variables be the same size.

Check out the binary conversion tool at the end of this guide to see how to pad your values to make them all the same size.

## Binary to Decimal JavaScript

We can also use JavaScript to convert a number from binary to decimal. In order to do that conversion we have to know about the power of two. Each binary digit represents a power of two.

The first one (from right to left) is two to the power of zero, i.e. 2^0 = 1.

The second one is 2^1 = 2.

The third is 2^2 = 4.

The fourth is 2^3 = 8

The fifth is 2^4 = 16.

And on and on it goes.

So in order to convert a decimal to binary we have to look at each individual digit, and if it is a one then we will raise 2 to the power of what index it is. We will start at the back of the string and move our way to the front.

function binaryToDecimal(binaryNumber){ var total = 0; for(var i = 0; i < binaryNumber.length; i++){ var bit = binaryNumber.charAt(binaryNumber.length - (i + 1 )); if(bit == 1){ var temp = Math.pow(2, i* parseInt(bit)); total += temp; } } return total; }

Using these two techniques we are now going to build our own text to binary converter.

## Building a Text To Binary Converter in JavaScript

We will have a text box where the user can enter some text, and then a button which will initiate the process of converting the ASCII text into a binary format. We will then display the output in a second text box that the user cannot edit. We will have radio buttons which will determine if we are converting from ASCII to binary, or if we are going to convert from binary back to regular text. Table Of Contents

### Creating our HTML structure

We will need the following HTML elements for our application.

- Text area one – For accepting user input
- Test area two – For displaying our output
- Button – To initiate the conversion
- Two radio buttons – To determine if we are converting from ASCII to binary or from binary to ASCII

Lets get started creating our HTML elements.

#### 1. Text Area One

<textarea id="userInput">

This is some default input.

Please type your own text here.

</textarea>

#### 2. Text Area Two

<textarea id="output" readonly>

Output will be placed here

</textarea>

#### 3. Button

<button id="startConversion">Start Conversion</button>

#### 4. Radio buttons

<input type="radio" id="asciiToBinary" name="conversion" checked="checked" value="0">

<label for"asciiToBinary">ASCII to Binary</label><br>

<input type="radio" id="binaryToAscii" name="conversion" value="1">

<label for"binaryToAscii">Binary to ASCII</label><br>

We now have all the HTML elements that we need for our binary converter. I am going to embed this HTML at the bottom of this page along with the CSS and JS so that you can try it out. If you are writing this in an IDE then the HTML, CSS, and JS should be in their own files. You would import the CSS and JS files in the header and it would work pretty much the same as the final solution at the end of this guide.

### Styling our HTML elements

We are going to add just a little bit of styling to our application to make it look a little better.

#### 1. Text boxes

We want to make the text boxes a little taller to begin with so that there is enough room to display the result.

<style>

textarea{

height: 200px;

}

</style>

#### 2. Button

We want to make the button a block element and also change the background color. This is because of how buttons work by default on this WordPress theme. The button is white so it is a bit difficult to see that it is actually a button. We also want to add some spacing around the button by applying a margin.

<style>

#startConversion{

background-color: #dedede;

display: block;

margin: 20px 0px;

}

</style>

### Adding JavaScript Logic

For our application we are going to create the following functions:

- getTextFromTextArea(id) – To get the text from a text area with the given id
- characterToAscii(character) – Convert a given character to ASCII
- asciiToBinary(ascii) – We will use this function to turn an ASCII character into a binary number
- binaryToAscii(binary) – Convert a binary number to an ASCII number
- asciiToCharacter(ascii) – Convert an ASCII number to a character
- getSelectedOption() – Get the selected radio button option so that we can perform the correct action

Lets get started working on the individual parts and then we will piece it all together at the end.

#### 1. getText(id)

This function will look for an element with the id that we give it. It will then get the value of that object and return it.

function getTextFromTextArea(id){

return document.getElementById(id).value + '';

}

#### 2. characterToAscii(character)

The next function we want to create is one that will take in an ASCII character and convert it to its binary equivalent.

function characterToAscii(character){

return character.charCodeAt();

}

#### 3. asciiToBinary(ascii)

We then have the binary representation of a word. One big difference with this function compared to the other code earlier in the guide is that here we will pad each binary number so that each chunk is a byte (8 bits). We need each chuck to be the same size because we need to know how much to grab at a time when we convert the data back to text. If you want to do something else than ASCII then you might have to have more space than 1 byte to represent the character.

function asciiToBinary(ascii){

var binary = "";

var temp = ascii;

while(temp > 0){

if(temp % 2 == 0){

binary = "0" + binary;

}

else {

binary = "1" + binary;

}

temp = Math.floor(temp / 2);

}

while(binary.length % 8 != 0){

binary = "0" + binary;

}

return binary;

}

#### 4. binaryToAscii(binary)

function binaryToAscii(binary){

var total = 0;

for(var i = 0; i < binary.length; i++){

var bit = binary.charAt(binary.length - (i + 1));

if(bit == 1){

var temp = Math.pow(2, i* parseInt(bit));

total += temp;

}

}

return total;

}

#### 5. asciiToCharacter(ascii)

This function will take in an ASCII number and convert it back into a character. We need this function for when we are going to covert back from binary to text.

function asciiToCharacter(ascii){

return String.fromCharCode(ascii);

}

#### 6. getSelectedOption()

The last thing we need is a function to get the selected option. We need this so that we can determine if we are going to convert from binary to text or from text to binary. We will return the value of the selected option. If you want to learn all the ways to use break and coninue in a for loop like we do below then check out this guide.

function getSelectedOtpion(){

var value = 0;

var allRadioOptions = document.getElementsByName("conversion");

for(var i = 0; i < allRadioOptions.length; i++){

if(allRadioOptions[i].checked){

value = allRadioOptions[i].value;

break;

}

}

return value;

}

### Putting our JavaScript Code Together

We now have most of the functionality we need, we just need to piece it all together. Here we will also create the *onClick *function that will initiate our code once we click the button. We also need to create the logic of looping over characters when converting to binary, and looping over a set of bytes at a time when converting from binary to text.

var button = document.getElementById("startConversion");

button.addEventListener("click", function(){

convert();

});

function convert(){

var converted = "";

var text = getTextFromTextArea("userInput");

var selectedValue = getSelectedOtpion();

if(selectedValue == 0){

converted = covertToBinary(text);

} else {

converted = convertToText(text)

}

document.getElementById("output").innerHTML = converted;

}

function covertToBinary(text){

console.log("Converting to binary");

var binary = "";

for(var i = 0; i < text.length; i++){

var ascii = characterToAscii(text.charAt(i));

binary += asciiToBinary(ascii);

}

console.log(binary);

return binary;

}

function convertToText(text){

console.log("Converting to text");

var content = "";

var index = 0;

for(var i = 0; i < text.length; i += 7){

if(index + 8 <= text.length){

var byte = text.substr(index, 8);

var ascii = binaryToAscii(byte);

var temp = asciiToCharacter(ascii);

index += 8;

content = content + temp;

}

}

console.log(content);

return content;

}

function getTextFromTextArea(id){

return document.getElementById(id).value + '';

}

function getSelectedOtpion(){

var value = 0;

var allRadioOptions = document.getElementsByName("conversion");

for(var i = 0; i < allRadioOptions.length; i++){

if(allRadioOptions[i].checked){

value = allRadioOptions[i].value;

break;

}

}

return value;

}

function characterToAscii(character){

return character.charCodeAt();

}

function asciiToBinary(ascii){

var binary = "";

var temp = ascii;

while(temp > 0){

if(temp % 2 == 0){

binary = "0" + binary;

}

else {

binary = "1" + binary;

}

temp = Math.floor(temp / 2);

}

while(binary.length % 8 != 0){

binary = "0" + binary;

}

return binary;

}

function binaryToAscii(binary){

var total = 0;

for(var i = 0; i < binary.length; i++){

var bit = binary.charAt(binary.length - (i + 1));

if(bit == 1){

var temp = Math.pow(2, i* parseInt(bit));

total += temp;

}

}

return total;

}

function asciiToCharacter(ascii){

return String.fromCharCode(ascii);

}

## Working Application

I have embedded our application below so that you can try it out. If you like it please check out some of our other projects on the Projects page.

Try writing your own text in the box below. Once you click the button you will get the output in binary. You can copy paste the binary back into the input box to translate it back to text. This application will work with any binary code where each character is represented by on byte.