进制互换
字符串转ascii码,用charCodeAt();
ascii码转字符串,用fromCharCode();
var str = "A";
var code = str.charCodeAt();
var str2 = String.fromCharCode(code);
十进制转二进制
var a = "i";
console.log(a.charCodeAt()); //105
console.log(a.charCodeAt().toString(2)); //1101001
将字符串转换成二进制形式,中间用空格隔开
function strToBinary(str){
var result = [];
var list = str.split("");
for(var i=0;i<list.length;i++){
if(i != 0){
result.push(" ");
}
var item = list[i];
var binaryStr = item.charCodeAt().toString(2);
result.push(binartStr);
}
return result.join("");
}
console.log(strToBinary("我们")); //110001000010001 100111011101100
console.log(strToBinary("@%$+")); //1000000 100101 100100 101011
将二进制字符串转换成Unicode字符串
function binaryToStr(str){
var result = [];
var list = str.split(" ");
for(var i=0;i<list.length;i++){
var item = list[i];
var asciiCode = parseInt(item,2);
var charValue = String.fromCharCode(asciiCode);
result.push(charValue);
}
return result.join("");
}
console.log(binaryToStr("110001000010001 100111011101100")); //我们
console.log(binaryToStr("1000000 100101 100100 101011")); //@%$+
字符串转换为十六进制
function stringToHex(str){
var val="";
for(var i = 0; i < str.length; i++){
if(val == "")
val = str.charCodeAt(i).toString(16);
else
val += "," + str.charCodeAt(i).toString(16);
}
return val;
}
十六进制转换为字符串
function hexToString(str){
var val="";
var arr = str.split(",");
for(arr i = 0; i < arr.length; i++){
val += arr[i].fromCharCode(i);
}
return val;
}
parseInt(string, radix) 方法只能转换 String 类型,对其它类型都返回 NaN(非数字)。string 表示待转换的字符,radix 表示要转为的进制