javascript - 二进制到十进制转换器问题
问题描述
我一直在尝试对这段代码进行故障排除,但什么都没有想到。预期结果如下...
- 我在文本框中输入了一个 6 位或更少的二进制数。
- 我按下“转换”按钮。
- 一小段将显示二进制数的十进制等效值。
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>
解决方案
一个较小的算法是这样的:
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>
推荐阅读
- c# - 我可以在 Xamarin.Forms 中直接使用 ListView 的 TemplatedItems 来更新属性吗?
- sql - 数据库查询选择最近的日期 - MAX 不起作用
- ansible - 当我在角色中包含剧本时,ansible错误冲突主机,任务
- javascript - 在 Gridsome 中加载 lottie JSON 文件
- c++ - 打印单链表的头尾
- r - 更改 SpatialLinesDataFrame 坐标以适应 shapefile
- python - 安装pyqt5==5.14.0后,错误显示为Could not load the Qt platform plugin "xcb" in "",即使找到了
- python-3.x - 无法通过破折号更改 Hr 元素的颜色
- javascript - 函数中带有字符串的打字稿条件总是返回 false
- ios - 如何在 SwiftUI 中使用cornerRadius 为视图创建前导边框?