1 //字符串转ascii码,用charCodeAt(); 2 //ascii码转字符串,用fromCharCode(); 3 var str = "A"; 4 var code = str.charCodeAt(); 5 var str2 = String.fromCharCode(code);
十进制转二进制
1 var a = "i"; 2 console.log(a.charCodeAt()); //105 3 console.log(a.charCodeAt().toString(2)); //1101001
1 var a = "我"; 2 console.log(a.charCodeAt()); //25105 3 console.log(a.charCodeAt().toString(2)); //110001000010001
1 var a = "我们"; 2 console.log(a.length); //2 3 var list = a.split(""); 4 console.log(list.length); //2<br>console.log(a.charCodeAt().toString(2)); //110001000010001 100111011101100
1 //将字符串转换成二进制形式,中间用空格隔开 2 function strToBinary(str){ 3 var result = []; 4 var list = str.split(""); 5 for(var i=0;i<list.length;i++){ 6 if(i != 0){ 7 result.push(" "); 8 } 9 var item = list[i]; 10 var binaryStr = item.charCodeAt().toString(2); 11 result.push(binartStr); 12 } 13 return result.join(""); 14 } 15 16 console.log(strToBinary("我们")); //110001000010001 100111011101100 17 console.log(strToBinary("@%$+")); //1000000 100101 100100 101011 18 19 //将二进制字符串转换成Unicode字符串 20 function binaryToStr(str){ 21 var result = []; 22 var list = str.split(" "); 23 for(var i=0;i<list.length;i++){ 24 var item = list[i]; 25 var asciiCode = parseInt(item,2); 26 var charValue = String.fromCharCode(asciiCode); 27 result.push(charValue); 28 } 29 return result.join(""); 30 } 31 32 console.log(binaryToStr("110001000010001 100111011101100")); //我们 33 console.log(binaryToStr("1000000 100101 100100 101011")); //@%$+