JavaScript中字符串与16进制之间的转换⼀、字符串转换为16进制
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>字符串转16进制</title>16进制字符串转16进制数组
<link rel="stylesheet" href="">
</head>
<body>
<input type="text" id="demo1">
<button onclick="stringToHex()">字符串转16进制</button>
<p id="demo2"></p>
<script>
function stringToHex(){
var str = ElementById("demo1").value;
var val = "";
for (var i = 0; i < str.length; i++) {
if (val == "") {
val = str.charCodeAt(i).toString(16);        //获取字符的Unicode码然后转16进制
} else {
val += "," + str.charCodeAt(i).toString(16);//获取字符的Unicode码然后转16进制再拼接,中间⽤逗号隔开
}
}
}
</script>
</body>
</html>
⼆、⼗六进制转字符串
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>⼗六进制转换为字符串</title>
<link rel="stylesheet" href="">
</head>
<body>
<input type="text" id="demo1">
<button onclick="hexToString()">⼗六进制转字符串</button>
<p id="demo2"></p>
<script>
/**
* 将16进制字符串进⾏分组,每两个⼀组
* @param  {[String]} str [16进制字符串]
* @return {[Array]}    [16进制数组]
*/
function groupArray(str){
var result = new Array();
for (var i = 0; i < str.length/2; i++) {
var aa = str.slice(i*2, (i+1)*2);
result.push(aa);
}
return result;
}
function hexToString(){
var str = ElementById("demo1").value;
var arr = groupArray(str);    //将16进制字符串进⾏每两个分组
var val = "";
for (var i = 0; i < arr.length; i++) {
val += String.fromCharCode(parseInt(arr[i], 16));    //将分组后的16进制字符串转10进制Unicode码,然后将Unicode码转换为字符            }
}
</script>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。