简体   繁体   English

在javascripts中用汉字将十六进制解码为字符串

[英]Decode Hex to String with Chinese characters in javascripts

I convert hex to string.我将十六进制转换为字符串。 I have hexstring: "0xe4b883e5bda9e7a59ee4bb99e9b1bc" and use this code:我有十六进制字符串:“0xe4b883e5bda9e7a59ee4bb99e9b1bc”并使用以下代码:

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.请帮帮我,谢谢。

The hex string represents the Chinese text encoded as a sequence of bytes using UTF-8 encoding.十六进制字符串表示使用 UTF-8 编码的字节序列编码的中文文本。

If you remove the leading "0x" from the hex string and insert a '%' character before each two characters, you get a string like this:如果从十六进制字符串中删除前导“0x”并在每两个字符前插入一个 '%' 字符,则会得到如下字符串:

%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:这就是它在 URI 中的外观,您可以使用decodeURIComponent从 UTF-8 解码它,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM