javascript - 二进制转换程序

标签 javascript math binary

我正在尝试编写一个程序,将十进制数转换为最多 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/

相关文章:

javascript - 应用‘主控’范围

JavaScript 使用 Jinja 模板中呈现的数据引发 SyntaxError

javascript - 根据连接计算网格布局?

python - 将 Pandas 数据框中的整数二值化

c - 将二进制值存储到无符号 int 数组中

javascript 将数组 1 中的字母替换为数组 2 中的数字并计算这些数字的总和

javascript - Alpine 嵌套 x 数据

C++ 在数学方程式中使用 E

ios - 使用磁力计、加速度计和陀螺仪读数的算法找到加速的基本方向

binary - 打字时如何表示不同的数字系统?