How to create a Binary to Decimal Converter with JavaScript

June 8th, 2006

This is an example of how a Binary to Decimal(and vice versa) Converter can be created with JavaScript. The script could – with some minor changes – be inserted within <script> tags in the head section of a HTML document, but since I like separating structure from function I have put it in an external .js file.

The JavaScript Code for the Converter

This JavaScript it is fully functional as it is, but feel free to do any changes you like. Maybe you want a different event to trigger computation, or maybe you want different error messages displayed when a user enter something the script cannot understand, such as letters instead of numbers.

Whatever you like to change it should be easy by simply changing the values of the global variables. If you want to change the event from keyup to keydown – for example – you simply change the value of that variable.

I use the Binary to Decimal Converter myself in the Web Resources section of this site. You can try it here: Binary to Decimal Converter.
If you want to use this converter script you can download the .js file here: convertToBinaryOrDecimal.js, or you can do some copy and paste with the code below.

/*Is DOM supported?*/
var ie = (document.all) ? true:false; // IE4+
var dom = ((document.getElementById) && (!ie)) ? true:false; // Mozilla
var input; //User input
var result; //Computed result
var placeholder; //128 64 32 16 8 4 2 1 are examples of the 8 placeholders in a byte
var base = 2; //Binary number system use base 2; either 1 or 0.
var binToDec = "binaryToDecimal"; //Flag for binary to decimal
var decToBin = "decimalToBinary";//Flag for decimal to binary
var binInputId = "binary-input" //id of the HTML input element for binary numbers
var decInputId = "decimal-input" //id of the HTML input element for decimal numbers
var event = "keyup"; //Event that triggers computation. Can of course be changed to fit you needs.
var binErrMsg = "Invalid input. Must be 1 or 0."; //Error message for invalid input in the binary field. Can of course be changed to fit your needs.
var decErrMsg = "Invalid input. Must be an integer between 0-9."; //Error message for invalid input in the decimal field
var unknownErrMsg = "Unknown error. Invalid input?"; //Error message for unknown errors
Can of course be changed to fit your needs.

/*Calls to the help function*/
setEventById(binInputId, event, function(){converter(binToDec);return false;});
setEventById(decInputId, event, function(){converter(decToBin);return false;});

/*Help function to set event listeners for browsers that support DOM and those who don't*/
function setEventById(id, ev, fu) {
document.getElementById(id).addEventListener(ev, fu, false);
document.getElementById(id).attachEvent('on' + ev, fu);

/*Help function used for validating the decimal input field. It should contain only Integers between 0-9*/
function isInteger(s) {
var validChars = "0123456789";
var isNumber=true;
var c;
for (i = 0; i < s.length && isNumber == true; i++) { c = s.charAt(i); if (validChars.indexOf(c) == -1) isNumber = false; } return isNumber; } /*The converter function. Takes a flag as input parameter. The flag can flag for binary conversion or decimal conversion*/ function converter(choice) { input = ""; result = ""; placeholder = 1; //Binary to Decimal if(choice == binToDec) { input = document.getElementById(binInputId).value; for(i=0; i <= input.length-1; i++) { if( input.charAt(i) != "0" && input.charAt(i) != "1") { document.getElementById(decInputId).value = binErrMsg; return false; } else if(i != 0) placeholder = placeholder * base; } result = eval( input.charAt(0)) * placeholder; for (i = 1; i <= input.length-1; i++) { placeholder = placeholder / base; result = result + (eval( input.charAt(i)) * placeholder); } if(isNaN(result)) result =""; document.getElementById(decInputId).value = result; } //Decimal to Binary else if(choice == decToBin) { try { input = document.getElementById(decInputId).value; //Must be an Integer if(!isInteger(input)) { document.getElementById(binInputId).value = decErrMsg; return false; } while(placeholder <= input) { placeholder = placeholder * base; } placeholder = placeholder / base; while (placeholder > 0.5) {
if( input >= placeholder) {
result = result + "1";
input = input - placeholder;
else if( input < placeholder) result = result + "0"; placeholder = placeholder / base; } if(isNaN(result)) result =""; document.getElementById(binInputId).value = result; } //Just in case of unpredictable errors catch(err) { document.getElementById(binInputId).value = unknownErrMsg; document.getElementById(decInputId).value = unknownErrMsg; } } } //End convertToBinaryOrDecimal

Linking to the Converter Script

The script can be linked to in the end of the <body> after the HTML markup used for your other page content such as the text and the <input> tags with the id’s described in the code above, like this:

The text you want, the two HTML input tags with the id's binary-input and decimal-input, and maybe some other content goes here....
<script type="text/javascript" src="convertToBinaryOrDecimal.js">

Entry Filed under: JavaScript

Bookmark with

Digg it?