javascript - 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(""));
}
解决方案
你可以这么简单:
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)
推荐阅读
- mongodb - 如何在 MongoDB 中复制文档中的字段?
- python - Twilio Media Stream 和 websocket 服务器 socketio python
- machine-learning - 栖息地挑战:运行DD-PPO脚本时遇到文件**.scn不存在错误
- python - 使用 CELF 的网络中的影响最大化
- powershell - PowerShell 和 conda 的 vscode 问题
- javascript - 为什么类 JS 执行两次?
- excel - Excel 表单控制按钮,可添加新行,但随表格移动
- javascript - 我应该如何将服务器返回的 aes 密钥存储在浏览器中?
- android - Jetpack compose dialogFragment 等效
- git - Git 拒绝跟踪某些文件(git add -f 不工作)