DEV Community

bryanvieta
bryanvieta

Posted on

Javascript to convert binary to hex

The numbering systems like binary, hexadecimal, and decimal are used by the electronic systems very heavily. All the computer motherboards and other electronic systems processors understand binary numbers only. If you want to communicate with the machine, then you need to send all the commands in binary numbers.

Here, in this article, I’m going to share the javascript code for binary to hex conversion. For one of my projects, I had to create a binary to hex converter to convert the binary values into hexadecimal and then store those values in the database.

When do you need to use a converter?

This converter is useful for the students. Along with students, if you are studying electronics or you are developing an internet of things the product or embedded system. I’m going to share the full code which you can just copy and paste and use in your project.

When I found out that I had to develop a converter, firstly, I had no idea about the numbering system. I wasted one-day understanding this and then I started developing the converter.
Code for binary to hex conversion:

var bin = document.getElementById("text_value").value;
var binn = bin.toString(2).toUpperCase();
document.getElementById("ans").innerHTML = binn;
Enter fullscreen mode Exit fullscreen mode

This is the code I found on StackOverflow. This code is great and it works well but there is a problem. This is good if you are looking to develop a tool for the students. If you want to develop a tool, then you need to make a few modifications to the code. You need to use a Javascript library called Bignumber.js. This library is used if you want to deal with large numbers.

When you are working with on an IoT product or an embedded system then you need to use the following code:

var bin = document.getElementById("text_value").value;
    var m = new BigNumber(bin, 16)
    var binn = m.toString(2).toUpperCase();   
document.getElementById("ans").innerHTML = binn;
Enter fullscreen mode Exit fullscreen mode

The Bignumber.js library is not an inbuilt library in Javascript. You need to import the script in the head tag. Just copy and paste the following code in the

tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/8.0.2/bignumber.min.js" integrity="sha512-7UzDjRNKHpQnkh1Wf1l6i/OPINS9P2DDzTwQNX79JxfbInCXGpgI1RPb3ZD+uTP3O5X7Ke4e0+cxt2TxV7n0qQ==" crossorigin="anonymous"></script>
Enter fullscreen mode Exit fullscreen mode

And done! You have built the binary to hex converter done. You can insert any binary number in the textbox and you will get the right hexadecimal result for the large numbers as well. If you made the converter with any other technique, then just share it by commenting below.

Top comments (0)