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...

问题:

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.


回答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);

  • 发表于 2019-01-09 17:54
  • 阅读 ( 192 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除