我正在尝试编写一个程序,将十进制数转换为最多 10 位的二进制数,但我无法弄清楚我当前的代码有什么问题。我对编程很陌生,所以我可能还没有掌握一些小东西。感谢您提供任何帮助,谢谢。
HTML 正文:
<!DOCTYPE html>
<html>
<head>
<title>Binary converter</title>
<script src="binaryConverter.js" type="text/javascript"></script>
</head>
<body>
<div>
<div>
<table>
<tr>
<td>Insert a decimal number to be converted to binary: </td>
<td>
<input type="text" id="decimal" placeholder="e.g. 54"></input>
</td>
<td>
<button type="button" onClick="calc()">Convert</button>
</td>
</tr>
<tr>
<td>Your result: </td>
<td id="resultCell"></td>
<td></td>
</tr>
</table>
</div>
</div>
</body>
</html>
JavaScript 主体:
function calc() {
var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
var decimal = document.getElementById("decimal").value;
result[9] == decimal % 2;
decimal == result[9];
result[8] == decimal % 2;
decimal == result[8];
result[7] == decimal % 2;
decimal == result[7];
result[6] == decimal % 2;
decimal == result[6];
result[5] == decimal % 2;
decimal == result[5];
result[4] == decimal % 2;
decimal == result[4];
result[3] == decimal % 2;
decimal == result[3];
result[2] == decimal % 2;
decimal == result[2];
result[1] == decimal % 2;
decimal == result[1];
result[0] == decimal % 2;
decimal == result[0];
document.getElementById("resultCell").innerHTML =
result[9].toString() +
result[8].toString() +
result[7].toString() +
result[6].toString() +
result[5].toString() +
result[4].toString() +
result[3].toString() +
result[2].toString() +
result[1].toString() +
result[0].toString();
}
```
最佳答案
您可能想单独读取每个二进制数字。您可以使用按位运算实现此目的:
>>>
向右移动一个数字:0b1000 >> 2 === 0b0010
&
执行按位与:(0b1001 & 0b1110) === 0b1000
使用这些运算符,您可以实现您的算法。
%
运算符将一个数除以另一个数并返回余数:15 % 2 === 1
, 1 % 2 === 1
关于javascript - 二进制转换程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59012506/