Javascript convert string to hex number and hex to string(charCodeAt, toString and parseInt)

Lionsure 2020-05-24 Original by the website

When you want to hide the characters, you can convert them into hexadecimal or binary. After several conversions between them, you may not see the original form. Once again, if the DBCS character set is also encrypted, it is even more necessary to convert to hexadecimal. Let's discuss how to convert a string to hexadecimal and how to convert hexadecimal to a string.

There are two ways to convert a string to hexadecimal in javascript. one, first converts the string to Unicode characters, then converts to hexadecimal, and finally intercepts four digits; the other, directly convert with parseInt(), but can only convert String type.

 

1. Javascript convert string to hex number

The conversion is mainly achieved by the charCodeAt() method, which returns the Unicode value of a characters, which is used to specify the index position. Then use toString(16) to convert Unicode value to hexadecimal, and finally use slice(-4) to intercept four digits from right.

function ConvertStringToHex(str) {
              var arr = [];
              for (var i = 0; i < str.length; i++) {
                     arr[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
              }
              return "\\u" + arr.join("\\u");
       }

Call:

var str = "strToHex";

ConvertStringToHex(str);//Output: \u0073\u0074\u0072\u0054\u006f\u0048\u0065\u0078

 

2. Convert hex to string javascript

Mainly achieved through the replace() and unescape() methods. First replace all \ in the string with % using replace(), then use unescape() to encode all characters (Unicode characters) in %uxxxx format with hexadecimal Unicode characters in xxxx format instead.

function ConvertHexToString(str) {
              return unescape(str.replace(/\\/g, "%"));
       }

Call:

var str = "\u0073\u0074\u0072\u0054\u006f\u0048\u0065\u0078";

ConvertStringToHex(str);//Output: strToHex

 

3. Use the parseInt() method to convert

The parseInt(string, radix) method can only convert the String type, and returns NaN(non-numeric) for other types; string(required argument) represents the character to be converted; radix(optional argument) represents the system to be converted, its value is between 2 ~ 36, if omitted, it will be converted to decimal.

Examples:

parseInt("ac", 16); //Convert the string "ab" to hexadecimal, result: 172

parseInt("12", 8); //Converts the string "12" to octal, result: 10

parseInt("10", 2); //Converts the string "10" to binary, result: 2