DEV Community

Cover image for How to Build Binary to Decimal Converter Using JavaScript
Stackfindover
Stackfindover

Posted on

How to Build Binary to Decimal Converter Using JavaScript

Hello guys, today I am going to show you how to create Binary to Decimal Converter Using Html CSS & JavaScript

What is binary to decimal converter?

This is a tool to convert binary numbers (010101) to decimal.

Binary to Decimal conversion table.

Binary Number : Decimal Number
10101 : 21
10110 : 22
10111 : 23
11000 : 24
11001 : 25

How to Create Binary to Decimal Converter Step by Step

Step 1 — Creating a New Project

The first thing we’ll do is create a folder that will contain all of the files that make up the project. Create an empty folder on your devices and name it “as you want”.

Open up Visual Studio Code or any Text editor, and create files(index.html, style.css, main.js) inside the folder. for creating Binary to Decimal Converter Tool. In the next step, you will start creating the structure of the webpage.

Step 2 — Setting Up the basic structure

In this step, we will add the HTML code to create the basic structure of the project.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">   
    <title>How to Create Binary to Decimal Converter Using JavaScript</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <script src="main.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is the base structure of most web pages that use HTML.

Add the following code inside the <body> tag:

<div class="binary_to_decimal">
    <div class="container">
      <h2>Binary to Decimal Converter</h2>
      <div class="form-row">
        <form>
          <div class="field">
            <label>
              <input type="text" name="bin" id="input" autocomplete="off" placeholder="Binary No.">
              <p>Binary</p>
            </label>
          </div>
          <div class="field">
            <label>
              <input type="text" name="dec" id="output" readonly="true" placeholder="Decimal No. will appear here">
              <p>Decimal</p>
            </label>
          </div>
          <div class="field btn-field">
            <button type="button" id="btn">Convert</button>
          </div>
        </form>
        <div id="error-msg">
          <p>You should enter a binary number composed by 0 and 1!</p>
        </div>
      </div>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

Step 3 — Adding Styles for the Classes

In this step, we will add styles to the section class Inside style.css file

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
* {
  margin: 0;
  padding: 0;
  border: none;
  outline: none;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
  -webkit-tap-highlight-color: transparent;
}
html,body {
  height: 100%;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f1f1f1;
}
.binary_to_decimal h2 {
  margin-bottom: 20px;
  font-size: 30px;
  color: #4766ff;
}
.binary_to_decimal {
  width: 100%;
  max-width: 500px;
  padding: 20px;
  background: #fff;
  border-radius: 0.2rem;
}
.field {
  margin-bottom: 15px;
}
.field label {
  position: relative;
}
.field label input {
  font-size: 1rem;
  color: #565656;
  background: transparent;
  padding: 1rem 1.2rem;
  min-width: 100%;
  border: 2px solid #565656;
  border-radius: 0.2rem;
}
.field label input:focus {
  border-color: #4766ff;
}
.field label p {
  color: #4766ff;
  font-size: 1rem;
  user-select: none;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  margin-left: 0.8rem;
  padding: 0 0.4rem;
  background: #fff;
  pointer-events: none;
  transition: top 0.2s, font-size 0.2s, color 0.2s;
}
.field label input:focus + p, .field label input:not(:placeholder-shown) + p {
  top: -20px;
  font-size: 0.9rem;
  color: #4766ff;
}
.field label input:not(:focus) + p {
  color: #565656;
}
button#btn {
  padding: 10px 20px;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  background: #4766ff;
  width: 100%;
  cursor: pointer;
  border-radius: 0.2rem;
}

div#error-msg {
  color: red;
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

Step 4 — Adding some lines of JavaScript code

In this step, we will add some JavaScript code to create binary to decimal converter tool.

const input = document.querySelector("#input");
const output = document.querySelector("#output");
const btn = document.querySelector("#btn");
const error = document.querySelector("#error-msg");


function Bin2Dec() {
    const regEx = /^[0-1]+$/;

    if(input.value.match(regEx)) {
        const binArr = input.value.split('').reverse();
        let decNo = 0;

        binArr.forEach((item, index) => item === '1' ? decNo += Math.pow(2, index) : void 0);

        output.value = decNo.toString();
        output.style.cursor = 'text';
    }else {
        error.style.display = 'block';
    }
}


btn.addEventListener('click', () => {
    error.style.display = 'none';
    Bin2Dec();
});
Enter fullscreen mode Exit fullscreen mode

Binary to Decimal Converter Tool Result

Top comments (4)

Collapse
 
efpage profile image
Eckehard

I tried the same using DML, bit shorter:

<!DOCTYPE html>
<html lang="de">

<head>
  <meta charset="utf-8">
  <title>title</title>
  <script src="https://efpage.de/DML/DML_homepage/lib/DML-min.js"></script>
  <style> body { font-family: sans-serif } </style>
</head>

<body>
  <script>  "use strict";
    // Make the input elements / key filter
    function myInput(txt, rule) {
      // Create text and input field
      idiv(txt, "width: 100px;")
      let inp = make("input", { value: 1 })
      br()

      // Key filter
      inp.onkeydown = (e) => { if (e.key.length == 1) if (!e.key.match(rule)) e.preventDefault() } // Filter keys
      return inp
    }

    // Build the page
    h1("Binary converter")
    sidiv("", _box + _bigPadding)
    let b = myInput("binary", "[0,1]")
    let d = myInput("decimal", "[0-9]")
    b.oninput = () => d.value = parseInt(b.value, 2)
    d.oninput = () => b.value = ( parseInt(d.value,10) >>> 0).toString(2);
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

binary

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

A shorter way to do the actual conversion (without using parseInt):

[...str].reverse().reduce((a,v,i)=>a+(+v?1<<i:0),0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Or even:

[...str].reduce((a,v)=>+v+a*2,0)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stackfindover profile image
Stackfindover

Awesome, Thanks for your suggestion bro :)