2

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.

TraN
  • 23
  • 1
  • 6
  • How did you get that hex string, shouldn't it be "4e035f69795e4ed99c7c"? – George Jan 08 '19 at 11:29
  • 0xe4b883e5bda9e7a59ee4bb99e9b1bc is the response from backend. In frontend I have to convert it into string and show. – TraN Jan 08 '19 at 11:40
  • What encoding is the backend using to encode the string it sends. Can you not specify this when fetching the data? – traktor Jan 08 '19 at 11:56
  • It's utf-8 encoding – TraN Jan 08 '19 at 12:23
  • The good news is that "e4b883e5bda9e7a59ee4bb99e9b1bc" is the UTF-8 sequence for "七彩神仙鱼". Converting it to UTF-32 and back to UTF-16 proves it. The bad news is that converting UTF encodings in JavaScript is usually the most complicated way of solving a problem. A better solution may be possible if you can explain **how** and **why** "七彩神仙鱼" is being sent as a hex string? – traktor Jan 08 '19 at 15:22
  • Correction: "e4b883e5bda9e7a59ee4bb99e9b1bc" is the hex representation of the UTF-8 byte sequence encoding of "七彩神仙鱼". UTF-8 uses between 1 and 4 bytes to encode a single Unicode codepoint. – traktor Jan 08 '19 at 15:43

1 Answers1

1

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);
traktor
  • 17,588
  • 4
  • 32
  • 53