javascript ASCII和Hex互转的实现方法

编程学习 2021-07-04 19:20www.dzhlxh.cn编程入门
狼蚁网站SEO优化长沙网络推广就为大家带来一篇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>

以上就是长沙网络推广为大家带来的javascript ASCII和Hex互转的实现方法全部内容了,希望大家多多支持狼蚁SEO~

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板