JavaScript中字符串与16进制之间的转换

一、字符串转换为16进制

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>字符串转16进制</title>
    <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 = document.getElementById("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进制再拼接,中间用逗号隔开
                }
            }
            document.getElementById("demo2").innerHTML = val;
        }
    </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 = document.getElementById("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码转换为字符
            }
            document.getElementById("demo2").innerHTML = val;
        }
    </script>
</body>
</html>

 

posted @ 2017-11-13 23:00  alsodzy  阅读(6995)  评论(0编辑  收藏  举报