Number to Bin Converter Using Javascript

Submitted by: 
Visitors have accessed this post 1103 times.

In this tutorial, I am going to teach you how to make a number to binary converter. You can also convert it to hexadecimal and octal representation.

To use this simple code just download the source code below.


First, we will be writing our html code.

  1. <b>Insert Decimal Number: </b><input type = "text" name = "deci" id = "deci" size = "15" maxlength = "15" />
  2. <input type="button" value="Convert!" onclick="dec2bin()" />
  3. <br><br>
  4. <div id = "result"></div>

This will be our javascript code.

  1. <script type = "text/javascript">
  3. function dec2bin() {
  4. var x = document.getElementById("deci").value;
  5. if ((/[^0-9]/g.test(x)) || x == "") {
  6. alert ("You must enter an integer decimal number!");
  7. document.getElementById("deci").value = "";
  8. document.getElementById("deci").focus();
  9. return false;
  10. }
  11. x = parseInt(x);
  12. var bin = x.toString(2);
  13. var hex = x.toString(16).toUpperCase();
  14. var octal = x.toString(8);
  17. var figs = "The binary representation of " + x + " is " + bin + "<br>";
  18. figs = figs + "The hexadecimal representation of " + x + " is " + hex + "<br>";
  19. figs = figs + "The octal representation of " + x + " is " + octal + "<br>";
  21. document.getElementById("result").innerHTML = figs;
  22. }
  23. </script>

Finally, you have created a simple converter of number to binary. For more suggestions, queries and questions, feel free to comment below.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.


1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.