我创建了一个 JavaScript 程序来将字符串转换为二进制。
Input: StackOverflow
Output: 1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111
现在我想将该二进制文件转换回如下所示的字符串。有没有可能的方法来做到这一点?
Input: 1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111
Output StackOverflow
Thanks
Use String.fromCharCode() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode and parseInt( , 2) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt像这样:
const binary = `1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111`;
const outputStr = binary
// split string into an array of base 2 (binary) UTF-16 chars
.split(' ')
// map every binary char to a UTF-16 number of base 10
// and then get the string representation of that UTF-16 number
.map(bin => String.fromCharCode(parseInt(bin, 2)))
// join the array back to a single string
.join('');
console.log(outputStr);
-
String.fromCharCode(number)
将从 UTF-16 字符代码返回一个字符串
-
parseInt(binary , 2)
将变换基数 2number字符串转换为以 10 为基数的数字
Edit:
As the String.fromCharCode()
函数接受多个字符作为参数,您也可以使用扩展运算符 (...) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax像这样:
const binary = `1010011 1110100 1100001 1100011 1101011
1001111 1110110 1100101 1110010 1100110
1101100 1101111 1110111`;
const outputStr = String.fromCharCode(
...binary.split(' ').map(bin => parseInt(bin, 2))
)
console.log(outputStr);
Edit 2:
随着时间的推移,这个答案会获得更多的流量,我还将添加解决方案,以相反的方式进行操作......以防万一:
const str = `StackOverflow`;
const outputStr = str.split('') // split in single chars
.map(c => c.charCodeAt(0) // get the UTF-16 code (10 base)
.toString(2)) // transform it back to a string (2 base)
.join(' ') // make single string from array
console.log(outputStr);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)