使用JavaScript将二进制转换为文本

27

我该如何使用 JavaScript 将二进制代码转换为文本?我已经成功将文本转换为二进制,但是有没有逆转的方法呢?

这是我的代码:

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;
  }
}
<div class="container">
  <span class="main">Binary Converter</span><br>
  <textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="convertBinary()"></textarea>
  <textarea class="outputBinary" id="outputBinary" readonly></textarea>
  <div class="about">Made by <strong>Omar</strong></div>
</div>

23个回答

47

我最近使用for循环完成了一项练习,希望对你有所帮助:

function binaryAgent(str) {

var newBin = str.split(" ");
var binCode = [];

for (i = 0; i < newBin.length; i++) {
    binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
  }
return binCode.join("");
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"

编辑:学习了更多的JavaScript后,我能够缩短解决方案:

function binaryAgent(str) {

var binString = '';

str.split(' ').map(function(bin) {
    binString += String.fromCharCode(parseInt(bin, 2));
  });
return binString;
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"

你正在使用.map,就好像你在使用.forEach一样。你可以使用const binaryAgent = str => str.split(' ').map(bin => String.fromCharCode(parseInt(bin, 2))).join("");代替。 - Константин Ван
4
啊,我卡在这个免费的编程营地的练习上了,我看到你也是从这里工作的 :) - Cloud
注意:这可能是O(n^2);在循环中连接字符串是一个不好的习惯...相反,你应该使用join方法,就像Jeffrey James所演示的那样。 - Nitsan BenHanoch

31
使用 toString(2) 将其转换为二进制字符串。例如:
var input = document.getElementById("inputDecimal").value;
document.getElementById("outputBinary").value = parseInt(input).toString(2);

如果您确定输入应该是十进制,则使用parseInt(input,10)。否则,输入"0x42"将被解析为16进制而不是10进制。

编辑:刚刚重新阅读了问题。要将二进制转换为文本,请使用parseInt(input,2).toString(10)

以上所有内容仅适用于数字。例如,4 <-> 0100。如果您想要4 <-> 十进制52(其ASCII值),请使用String.fromCharCode()(请参见这个答案)。

编辑2:根据要求的位置,尝试使用以下内容:

function BinToText() {
    var input = document.getElementById("inputBinary").value;
    document.getElementById("outputText").value = parseInt(input,2).toString(10);
}
...
<textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="BinToText()"></textarea>
<textarea class="outputBinary" id="outputText" readonly></textarea>

如果您在 inputBinary 中输入了 0100,则应在 outputText 中获得 4(未经测试)。

编辑以显示。进一步的建议:将您的函数命名为“X2Y”,而不是“convertX”。像“convertBinary”这样的名称并不立即清楚它是转换为二进制还是从二进制转换。使用更具描述性的函数和变量名称将有助于其他人更好地理解您的代码,并且当您一个月后回来时,也将帮助您更好地理解它 :)。 - cxw

9

如果还有人在寻找相关信息,与另一个答案类似。首先分割返回字符串列表,每个字符串代表一个二进制字符

然后我们对每个字符串调用map函数,例如 "11001111" 或其他字符串,并返回该元素上的fromCharCode和嵌套的parseInt。最后在返回值上使用.join(),就可以正常工作了。

function binaryAgent3(str) {

  return str.split(" ").map(function(elem) {
    return String.fromCharCode(parseInt(elem, 2));
  }).join("")

}

原始问题:http://www.freecodecamp.com/challenges/binary-agents


该问题涉及编程,需要转化为中文。请点击链接查看详细信息。保留HTML标签。

喜欢这个解决方案的简单易行。 - AndrewNeedsHelp

8

我遇到了同样的问题,想要将二进制转换为文本,这是我想出来的方法。

function binaryToWords(str) { 
    if(str.match(/[10]{8}/g)){
        var wordFromBinary = str.match(/([10]{8}|\s+)/g).map(function(fromBinary){
            return String.fromCharCode(parseInt(fromBinary, 2) );
        }).join('');
        return console.log(wordFromBinary);
    }
}

binaryToWords('01000011 01101111 01100110 01100110 01100101 01100101 00100000 01101001 01110011 00100000 01100011 01101111 01101100 01100100 ');

3

这是我编写的二进制转字符串的代码。唯一的区别是它更短,并依赖于内置的JS函数。

function binarytoString(str) {
  return str.split(/\s/).map(function (val){
    return String.fromCharCode(parseInt(val, 2));
  }).join("");
}

3

我为将二进制代码转换为文本的解决方案。没有多余的东西。我认为这是最简单的版本。

function binaryAgent(str) {
  return str.split(" ").map(x => String.fromCharCode(parseInt(x, 2))).join("");
}

console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));


2

如果您正在寻找一行解决方案。

function binary(str) {
return str.split(/\s/g).map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
}
//returns "one line"
binary("01101111 01101110 01100101 00100000 01101100 01101001 01101110 01100101");

2

如果您知道只传递二进制代码,那么您可以使用这个仅有一行简单代码的函数:

Original Answer翻译成"最初的回答"

function binaryAgent(str) {
  return str.split(" ").map(input => String.fromCharCode(parseInt(input,2).toString(10))).join("");

}

// Calling the function
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

2

更短的代码

function binaryAgent(str) {
  let array = str.split(" ");
  return array.map(code => String.fromCharCode(parseInt(code, 2))).join("");
}

console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
// should return "Aren't bonfires fun!?"


2
这个怎么样?
function binaryAgent(str) {
  var splitStr = str.split(" ");
  var newVar = splitStr.map(function(val) {
    return String.fromCharCode(parseInt(val,2).toString(10));
  });
  str = newVar.join("");
  return str;
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"); // should return "Aren't bonfires fun!?"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接