JavaScript binary to decimal application (Part Three): The Flux Capa… Convertor

Ok been on a hiatus due to work/college and most importantly my first born. So after a much waited delay, here’s the final piece – the actual conversion from Binary to Decimal.

This is the logic, which I took adapted from my Java lectures.

var convertToDecimal = function(binVal){
  var result = 0;
  var n = binVal.length - 1;
  for (i = 0; i < binVal.length; i++){
    var digit = binVal.charAt(i);
    result = result + (digit * Math.pow(2, n));
    n--;
  }
  return result;
}

This takes over from the last check, where we verified if an input was binary, and traverses the length of that input from left to right. Simultaneously var n is set to the positional power of the digit iterated over and added to the digit. The end result of all such additions is the decimal value.

Niggles encountered

I initially set the for loop check as n + 1; I erroneously assumed that since n was length minus one that would make up for the discrepancy, however each iteration would affect the value of n with the decrement (n–) and then the check would add 1 to it. I haven’t checked the full ramification of such a value but it did throw off conversion.

Another snag was that I was trying to set the output field’s value inside a conditional branch i.e.

if (value does not contain 1 or 0){  
  document.getElementById("output").value = input;
} else {
  /* code to execute if input is binary */
}

This was before, when I was doing a test to see output of invalid characters; input is the parameter passed to the function which contains the above conditional. That didn’t actually set the output as I’d expected. It somewhat makes sense when the function call is made – it is set to pass a value back, which expects a returned value.

document.getElementById("output").value = checkInput(binInput);

The line above can be taken to mean it would set it directly but wasn’t doing anything.

Closing Thoughts

So that pretty much wraps up the project in terms of the functionality and what was set out initially :

  • Creating a HTML/CSS/Javascript implementation of a problem we had to solve in a Java class – given a binary value, convert it to its decimal counterpart.
    • logic for the binary to decimal conversion.
    • restricting the entry value to 1’s and 0’s, probably using regular expression.

Further enhancements might be conducted to improve the user interface. One thing that came up during the exercise is that CodePen isn’t ideal for showing the various stages of the project. So each blog entry detailing the steps I’d taken will all point to the end result and not what it was like at that moment in time. Suppose that’s another issue to contend with if items are being created on CodePen. For the moment here is the completed, albeit unpolished, piece:

See the Pen Binary to Decimal Conversion by Donal D’silva (@donyd) on CodePen.