简体   繁体   English

将十六进制编码/解码为utf-8字符串

[英]Encode/decode hex to utf-8 string

Working on web application which accepts all UTF-8 character's including greek characters following are strings that i want to convert to hex. 在接受所有UTF-8字符(包括希腊字符)的Web应用程序上工作,以下是我想转换为十六进制的字符串。
Following are different language string which are not working in my current code 以下是在当前代码中不起作用的其他语言字符串

ЫЙБПАРО Εγκυκλοπαίδεια éaös Größe Größe ЫЙБПАРО Εγκυκλοπαίδεια éaös Größe Größe

Following are hex conversions by javascript function mentioned below 以下是通过下面提到的javascript函数进行的十六进制转换

42b41941141f41042041e 3953b33ba3c53ba3bb3bf3c03b13af3b43b53b93b1 e961f673 4772c3192c2b6c3192c217865 4772f6df65 42b41941141f41042041e 3953b33ba3c53ba3bb3bf3c03b13af3b43b53b93b1 e961f673 4772c3192c2b6c3192c217865 4772f6df65

Javascript function to convert above string to hex Javascript函数将上述字符串转换为十六进制

function encode(string) {
     var str= "";
        var length = string.length;        
        for (var i = 0; i < length; i++){
            str+= string.charCodeAt(i).toString(16);
            }
        return str;
}

Here it is not giving any error to convert but at java side I'm unable to parse such string used following java code to convert hex 在这里它不会给转换带来任何错误,但在Java端,我无法解析以下用Java代码转换十六进制的字符串

public String HexToString(String hex){

          StringBuilder finalString = new StringBuilder();
          StringBuilder tempString = new StringBuilder();

          for( int i=0; i<hex.length()-1; i+=2 ){                
              String output = hex.substring(i, (i + 2));             
              int decimal = Integer.parseInt(output, 16);            
              finalString.append((char)decimal);     
              tempString.append(decimal);
          }
        return finalString.toString();
    }

It throws error while parsing above hex string giving parse exception. 在解析上面的十六进制字符串时会抛出错误,从而导致解析异常。 Suggest me the solution 向我建议解决方案

Javascript works with 16-bit unicode characters, therefore charCodeAt might return any number between 0 and 65535. When you encode it to hex you get strings from 1 to 4 chars, and if you simply concatenate these, there's no way for the other party to find out what characters have been encoded. Javascript使用16位unicode字符,因此charCodeAt可能返回0到65535之间的任何数字。将其编码为十六进制时,您会得到1到4个字符的字符串,并且如果您简单地将它们连接起来,则另一方无法找出已编码的字符。

You can work around this by adding delimiters to your encoded string: 您可以通过在编码字符串中添加定界符来解决此问题:

 function encode(string) { return string.split("").map(function(c) { return c.charCodeAt(0).toString(16); }).join('-'); } alert(encode('größe Εγκυκλοπαίδεια 维')) 

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

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