使用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个回答

0
这是我的解决方案,尽可能使用ES6语法:
const binaryAgent = str => {
    let code = str.split(" ")
    let s = code.map((d) => parseInt(d,2))
    let res = s.map((d) => String.fromCharCode(d))
    return res.join("")
}

binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")

它应该返回我爱FreeCodeCamp!


0
const whoTookTheCarKey = message => 
  message.toString().split(',')
     .map(message => String.fromCharCode(parseInt(message, 2)))
     .join('')enter code here

欢迎来到StackOverflow。虽然这段代码可以解决问题,但是提供如何以及为什么解决问题的解释会真正帮助提高您的文章质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释,并指出适用的限制和假设条件。 - Federico Baù

-1
这是对JosephD的“一行(箭头)函数”答案的微小调整...
当箭头函数只有一个参数时,您可以省略括号()。您可以在箭头函数和.map方法中都省略它们,如下所示:
let binToStr = str => str.split(' ').map(x => String.fromCharCode(parseInt(x,2))).join('');

一个类似的建议已经在其他答案的评论中提出。 - gionni

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