Binary to Decimal Converter Issues

Viewed 55

I have been trying to troubleshoot this code, but nothing is coming to mind. The expected result is as follows...

  1. I enter a binary number of 6 digits or less into the textbox.
  2. I press the "Convert" button.
  3. A short paragraph will display the decimal equivalent of the binary number.

var BinIN = document.getElementById("binaryInput").value;
let DecOUT = 0;

function compute() {
  if ((BinIN.charAt(0) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 1);
  }

  if ((BinIN.charAt(1) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 2);
  }

  if ((BinIN.charAt(2) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 3);
  }

  if ((BinIN.charAt(3) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 4);
  }

  if ((BinIN.charAt(4) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 5);
  }

  if ((BinIN.charAt(5) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 6);
  }

  if ((BinIN.charAt(6) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 7);
  }

  if ((BinIN.charAt(7) = 1)) {
    DecOUT += Math.pow(2, BinIN.length - 8);
  }

  document.getElementById("DecimalOutput").innerHTML = DecOUT;
}
<label for="binaryInput">Binary</label><br />

<input type="text" id="binaryInput" name="binaryInput" value="0" /><br />

<button onclick="compute()">Convert</button>

<p id="DecimalOutput"></p>

1 Answers

A smaller algo would be this:

function compute() {
  var BinIN = document.getElementById("binaryInput").value;
  document.getElementById("DecimalOutput").innerHTML = parseInt(BinIN, 2);
}
<label for="binaryInput">Binary</label><br />

<input type="text" id="binaryInput" name="binaryInput" value="0" /><br />

<button onclick="compute()">Convert</button>

<p id="DecimalOutput"></p>

Related