How to convert JS strings to hexadecimal
Mar 07, 2018 pm 01:13 PM开发过程中,字符串与十六进、二进制之间的相互转换常常会用到,尤其是涉及到中文的加密时,就需要把中文转换为十六进制。下面说说具体的转换方法。
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; }
调用方法:
var str = "abcde"; stringToHex(str); stringToHex('AB中国中國'); -- 结果: 41,42,4e2d,56fd,4e2d,570b
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);
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
var str = "abcdeghijklmnopqrstuvwxyz"; console.log(stringToHex(str)); str="http://www.qq.com"; len=str.length; arr=[]; for(var i=0;i<len;i++){ arr.push(str.charCodeAt(i).toString(16)); } console.log("\\x"+arr.join("\\x"));
相关推荐:
JavaScript进阶(四)js字符串转换成数字的三种方法
The above is the detailed content of How to convert JS strings to hexadecimal. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of the method of converting int type to string in PHP

How to determine whether a Golang string ends with a specified character

How to check if a string starts with a specific character in Golang?

How to repeat a string in python_python repeating string tutorial

How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP

PHP string manipulation: a practical way to effectively remove spaces

PHP String Matching Tips: Avoid Ambiguous Included Expressions

PHP techniques for deleting the last two characters of a string
