TraN
TraN

Reputation: 23

Decode Hex to String with Chinese characters in javascripts

I convert hex to string. I have hexstring: "0xe4b883e5bda9e7a59ee4bb99e9b1bc" and use this code:

hex_to_ascii(str1){
  var hex  = str1.toString().substring(2, str1.length);
  var str = '';
  for (var n = 0; n < hex.length; n += 2) {
    str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
  }
  return str;
}

the correct response must be "七彩神仙鱼", but my response is "ä¸å½©ç¥ä»é±¼". What's wrong with my code. Please help me, thanks.

Upvotes: 2

Views: 1431

Answers (1)

traktor
traktor

Reputation: 19301

The hex string represents the Chinese text encoded as a sequence of bytes using UTF-8 encoding.

If you remove the leading "0x" from the hex string and insert a '%' character before each two characters, you get a string like this:

%e4%b8%83%e5%bd%a9%e7%a5%9e%e4%bb%99%e9%b1%bc

This is how it would look in a URI and you can decode it back from UTF-8 using decodeURIComponent, as for example in:

"use strict";
var hex = "0xe4b883e5bda9e7a59ee4bb99e9b1bc";
hex = hex.substr(2);
hex = hex.replace( /../g , hex2=>('%'+hex2));
var string = decodeURIComponent(hex);
console.log(string);

Upvotes: 1

Related Questions