DEV Community


Posted on

Develop a full Binary Translator With Javascript

It has been over six months since I'm working on the IoT project where firstly, I created a binary to the decimal converter and now a binary translator. When I started working on the project I had no idea that I had to create a binary translator that converts binary to hexadecimal, decimal, and octal.

Honestly, I used to find binary translation boring when I was at school. And when I had to develop a binary translator, I found it difficult. So, I decided to share the code of a binary translator here, so that anyone with the need can use it to develop a tool easily.

Yes, you may find the code online especially on StackOverflow. But the code there does not return the correct answer for big numbers. I did not know about this issue with the code until my client drew my attention. So, I have decided to write a code that returns a correct answer for large numbers as well.

Binary translator:


<input type="text" id="text_value1" style="width: 100%" class="w3-border w3-padding-large w3-padding-32 w3-center" placeholder="Enter a value"/><br><br>
              <button onclick="binarytotext(); bintodec(); bintooct(); bintohex();" class="w3-button w3-border w3-teal w3-padding-large w3-hover-gray" style="display: inline-block">Convert</button>
Enter fullscreen mode Exit fullscreen mode

Javascript Function:

  function bintodec() {
    var dddd = document.getElementById("text_value1").value;
      var fa = parseInt(dddd)
      var cc = new BigNumber(parseInt(dddd, 2))
      if (isNaN(cc)) {
        document.getElementById("ans2").innerHTML = "This number cannot be converted into Decimal";
      } else {
        document.getElementById("ans2").innerHTML = cc;
    function bintooct() {
    var xxx = document.getElementById("text_value1").value;
    var bintooct = parseInt(xxx, 2).toString(8)
    if (isNaN(bintooct)) {
      document.getElementById("ans3").innerHTML = "This number cannot be converted into Octal";
    } else {
      document.getElementById("ans3").innerHTML = bintooct;
  function bintohex() {
    var binnn = document.getElementById("text_value1").value;
var mol = new BigNumber(binnn, 2)
var binnx = mol.toString(16)
if (isNaN(binnx)) {
document.getElementById("ans4").innerHTML = "This number cannot be converted into Hex";
} else {
document.getElementById("ans4").innerHTML = binnx;

Enter fullscreen mode Exit fullscreen mode

In the code, I have used the big number javascript library to convert big numbers into decimal, hexadecimal, and octal. If we do not use this library then it becomes difficult for Javascript to perform such conversion. After reading this article, feel free to share anything regarding binary translator with me.

Discussion (0)