按位取反可视化工具(~x)

按位取反可视化工具(~x)

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>按位取反可视化工具</title>
    <style>
        body { font-family: sans-serif; padding: 20px; background: #f5f5f5; }
        .card { background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); max-width: 600px; margin: auto; }
        input { width: 100%; padding: 10px; font-size: 16px; margin-top: 10px; }
        select { padding: 8px; font-size: 14px; margin-top: 10px; }
        pre { background: #222; color: #0f0; padding: 15px; border-radius: 8px; overflow-x: auto; }
    </style>
</head>
<body>
<div class="card">
    <h2>按位取反可视化工具(~x)</h2>
    <label>输入一个整数:</label>
    <input id="numInput" type="number" value="5" />

    <label>选择位宽:</label><br />
    <select id="bits">
        <option value="8">8 位</option>
        <option value="16">16 位</option>
        <option value="32" selected>32 位</option>
    </select>

    <pre id="output"></pre>
</div>

<script>
    function toBinary(n, bits) {
        let mask = (1 << bits) - 1;
        let b = (n & mask).toString(2).padStart(bits, '0');
        return b.replace(/(.{4})/g, '$1 ');
    }

    function compute() {
        const x = parseInt(document.getElementById("numInput").value);
        const bits = parseInt(document.getElementById("bits").value);
        const mask = (2 ** bits) - 1;

        const notx = (~x) & mask;

        const binX = toBinary(x, bits);
        const binNot = toBinary(notx, bits);

        const signedNot = notx >= 2 ** (bits - 1) ? notx - 2 ** bits : notx;

        document.getElementById("output").textContent =
            `输入值 x = ${x}
二进制 (${bits} 位):
${binX}

~x 结果(二进制):
${binNot}

~x 作为有符号整数 = ${signedNot}
~x 作为无符号整数 = ${notx}`;
    }

    document.getElementById("numInput").addEventListener("input", compute);
    document.getElementById("bits").addEventListener("change", compute);
    compute();
</script>
</body>
</html>

posted @ 2025-12-03 10:10  爱新觉罗LQ  阅读(5)  评论(0)    收藏  举报