首页 > 解决方案 > Javascript二进制数转成一句话

问题描述

我需要将这些二进制数转换为一个句子。

所以...

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

应该返回“篝火不好玩吗!?”

我写了下面的代码,但它什么也没返回。
我知道有比这种方式更好的解决方案,但我首先想知道为什么我的代码不起作用。
有人乐意帮助我吗?

function binaryAgent(str) {
  let arr = str.split(" ").map(x => x.split(""));
  let newArr = [];
  let num = 0;

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].lnegth; j++) {
      if (arr[i][j] === "1") {
        num += 2 ** (7 - j);
      }
      newArr.push(num);
    }
  }

  return String.fromCharCode(newArr.join(""));
}

标签: javascript

解决方案


你可以这么简单:

const str = "01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111",

      sentence = str
        .split(' ')
        .reduce((acc, b) => 
          acc += String.fromCharCode(parseInt(b,2)), '')
        
console.log(sentence)


推荐阅读