JavaScript 字符串和二进制互相转换

4,219 阅读1分钟

背景

在JS里面字符串和二进制互相的转换,主要用到了 parseInt(str, 2) String.fromCharCode(asciiCode), 和 charCodeAt(), toString(2)

code

function binaryAgent(str) {
    let res = [];
    const arr = str.split(' ');
  	return arr.map(item => {
        let asciiCode = parseInt(item, 2);
        let charValue = String.fromCharCode(asciiCode);
        return charValue
    }).join('');
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
// 字符串转二进制
function strToBinary (str) {
    let list = str.split('');
    return list.map(item => {
        return item.charCodeAt().toString(2);
    }).join(' ');
}
strToBinary('我们')