我想制作二进制文本转换器。我已经为二进制转换器做了一个文本。这是代码:
function convertText() {
var output = document.getElementById("binaryConvert");
var input = document.getElementById("textConvert").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;
}
}
但我不知道如何将二进制文件转换为文本。谁知道?另外,如果它不是二进制的,那么它们在textConvert框中输入它的值为“那不是你输入的二进制”或类似的东西。这是我的所有代码:
<!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 convertText() {
var output = document.getElementById("binaryConvert");
var input = document.getElementById("textConvert").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;
}
}
</script>
<noscript>
Please enable JavaScript in your browsers settings to use this tool.
</noscript>
</head>
<body>
<center>
<div class="container">
<span class="main">Binary Converter</span><br>
<textarea class="textConvert" id="textConvert" onKeyUp="convertText()" placeholder="Input text to convert to Binary"></textarea>
<textarea class="binaryConvert" id="binaryConvert" placeholder="Binary text" readonly></textarea>
<div class="about">Made by <strong>Omar Latreche</strong></div>
</div>
</center>
</body>
</html>
编辑:我明白了。这是代码:
function convertBinary() {
var bintext, textresult="", binlength;
bintext = document.getElementById("text_result").value.replace(/[^01]/g, "");
binlength = bintext.length-(bintext.length%8);
for (z=0; z < binlength; z=z+8) {
textresult += String.fromCharCode(parseInt(bintext.substr(z,8),2));
}
document.getElementById("text_convert").value = textresult;
}
感谢所有答案!
答案 0 :(得分:3)
是的,使用上面建议的parseInt - 并考虑使用(+ input).toString(2)将输入转换为二进制:)
function convertText() {
var output = document.getElementById("binaryConvert");
var input = document.getElementById("textConvert").value;
output.value = (+input).toString(2);
}
function convertBinary() {
var output = document.getElementById("textConvert");
var input = document.getElementById("binaryConvert").value;
output.value = parseInt(input,2);
}
答案 1 :(得分:1)
答案 2 :(得分:1)
function binarytoString(str) {
return str.split(/\s/).map(function (val){
return String.fromCharCode(parseInt(val, 2));
}).join("");
}