zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Mybatis应用
    MyBatis
    jQuery中.bind() .live() .delegate() .on()的区别
    SpringMVC (八)SpringMVC返回值类型
    SpringMVC(七)参数的自动装配和路径变量
    SpringMVC (六)注解式开发
    SpringMVC (五)视图解析器
    SpringMVC (四)MultiActionController
    SourceTree的使用
    Idea中使用git
  • 原文地址:https://www.cnblogs.com/alsodzy/p/7828754.html
Copyright © 2011-2022 走看看