zoukankan      html  css  js  c++  java
  • javascript ASCII和Hex互转

    <script>
    
    var symbols = " !"#$%&'()*+,-./0123456789:;<=>?@";
    var loAZ = "abcdefghijklmnopqrstuvwxyz";
    symbols+= loAZ.toUpperCase();
    symbols+= "[\]^_`";
    symbols+= loAZ;
    symbols+= "{|}~";
    
    //Hex to ASCII
    function toAscii(str)
    {
        valueStr = str.toLowerCase();
        var hex = "0123456789abcdef";
        var text = "";
        var i=0;
    
        for( i=0; i<valueStr.length; i=i+2 )
        {
            var char1 = valueStr.charAt(i);
            if ( char1 == ':' )
            {
                i++;
                char1 = valueStr.charAt(i);
            }
            var char2 = valueStr.charAt(i+1);
            var num1 = hex.indexOf(char1);
            var num2 = hex.indexOf(char2);
            var value = num1 << 4;
            value = value | num2;
    
            var valueInt = parseInt(value);
            var symbolIndex = valueInt - 32;
            var ch = '?';
            if ( symbolIndex >= 0 && value <= 126 )
            {
                ch = symbols.charAt(symbolIndex)
            }
            text += ch;
        }
        return text;
    }
    //ASCII to Hex
    function toHex(str)
    {
        var valueStr = str;
        var hexChars = "0123456789abcdef";
        var text = "";
        for( i=0; i<valueStr.length; i++ )
        {
            var oneChar = valueStr.charAt(i);
            var asciiValue = symbols.indexOf(oneChar) + 32;
            var index1 = asciiValue % 16;
            var index2 = (asciiValue - index1)/16;
            if ( text != "" ) text += ":";
            text += hexChars.charAt(index2);
            text += hexChars.charAt(index1);
        }
        return text;
    }
    
    
    </script>
  • 相关阅读:
    C# Enum,Int,String的互相转换
    彻底弄懂css中单位px和em,rem的区别
    HTML特殊字符大全2
    网页特殊符号HTML代码大全
    HTML特殊字符大全
    收集一些特殊的符号
    jQuery 获取屏幕高度、宽度
    HTMLParser 使用详解
    C# 操作Word知识汇总
    C#编程总结(一)序列化
  • 原文地址:https://www.cnblogs.com/sprinng/p/5166051.html
Copyright © 2011-2022 走看看