将文本转换为二进制

将文本转换为二进制

我想将文本转换为二进制。例如,如果有人键入“ Hello”,它将返回0100100001100101011011000110110001101111我该怎么做?我已经尝试过了,但是出了点问题:

function convertBinary() {
    var output = document.getElementById("outputBinary");
    var input = document.getElementById("inputBinary").value;
    output.value = "";
    for (i=0; i < input.length; i++) {
        output.value +=input[i].charCodeAt(0).toString(2);
    }
}


这是我的代码:

<!doctype html>
<html>
<head>
<title>Binary Converter</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function convertBinary() {
    var output = document.getElementById("outputBinary");
    var input = document.getElementById("inputBinary").value;
    output.value = "";
    for (i=0; i < input.length; i++) {
        output.value +=input[i].charCodeAt(0).toString(2);
    }
}
</script>
</head>
<body>
<center>
<div class="container">
    <span class="main">Binary Converter</span><br>
    <input type="text" onKeyUp="convertBinary()" id="inputBinary" class="inputBinary" placeholder="Enter Text"><br>
    <input type="text" id="outputBinary" class="outputBinary" readonly>
</div>
</center>
</body>
</html>


任何帮助将不胜感激。谢谢,奥马尔。

最佳答案

function convertBinary() {
    var output = document.getElementById("outputBinary");
    var input = document.getElementById("inputBinary").value;
    output.value = "";
    for (i=0; i < input.length; i++) {var e=input[i].charCodeAt(0);var s = "";
    do{
        var a =e%2;
        e=(e-a)/2;
        s=a+s;
        }while(e!=0);
        while(s.length<8){s="0"+s;}
        output.value+=s;
    }
}


你欢迎我的朋友

07-28 07:18