Home > Web Front-end > JS Tutorial > body text

Js字符串相互转换十六进制的方法

小云云
Release: 2018-03-07 13:13:31
original
6487 people have browsed it

开发过程中,字符串与十六进、二进制之间的相互转换常常会用到,尤其是涉及到中文的加密时,就需要把中文转换为十六进制。下面说说具体的转换方法。

  1、字符串转换为十六进制

  主要使用 charCodeAt()方法,此方法返回一个字符的 Unicode 值,该字符位于指定索引位置。 

 function stringToHex(str){
    var val="";
    for(var i = 0; i < str.length; i++){
      if(val == "")
        val = str.charCodeAt(i).toString(16);
      else
        val += "," + str.charCodeAt(i).toString(16);
    }
    return val;
  }
Copy after login

  调用方法:
  

var str = "abcde";
  stringToHex(str);
       stringToHex('AB中国中國');    -- 结果: 41,42,4e2d,56fd,4e2d,570b
Copy after login
  2、十六进制转换为字符串

  主要使用 fromCharCode()方法,此方法将 Unicode 码转换为与之对应的字符。
 

 function hexToString(str){
    var val="";
    var arr = str.split(",");
    for(arr i = 0; i < arr.length; i++){
      val += arr[i].fromCharCode(i);
    }
    return val;
  }
  调用方法:
  var str = "676865";
  stringToHex(str);
Copy after login
  3、用 parseInt() 方法转换
 parseInt(string, radix) 方法只能转换 String 类型,对其它类型都返回 NaN(非数字)。string 表示待转换的字符,radix 表示要转为的进制,值介于 2 ~ 36 之间。
  parseInt("bc",16); //表示把字符串bc转换为16进制,结果:188
  parseInt("10",8); //表示把字符串10转换为8进制,结果:8
  parseInt("10",2); //表示把字符串10转换为2进制,结果:2
Copy after login
  var str = "abcdeghijklmnopqrstuvwxyz";  console.log(stringToHex(str));
  str="http://www.qq.com";  len=str.length;  arr=[]; 
   for(var i=0;i
Copy after login

相关推荐:

JavaScript进阶(四)js字符串转换成数字的三种方法

The above is the detailed content of Js字符串相互转换十六进制的方法. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!