首页 > 解决方案 > 二进制到十进制转换器问题

问题描述

我一直在尝试对这段代码进行故障排除,但什么都没有想到。预期结果如下...

  1. 我在文本框中输入了一个 6 位或更少的二进制数。
  2. 我按下“转换”按钮。
  3. 一小段将显示二进制数的十进制等效值。

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>

标签: javascripthtmlbinary

解决方案


一个较小的算法是这样的:

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>


推荐阅读