本文介绍了将十六进制编码/解码为utf-8字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在接受所有UTF-8字符(包括希腊字符)的Web应用程序,下面是我要转换为十六进制的字符串。

以下是在当前代码中不起作用的其他语言字符串

Working on web application which accepts all UTF-8 character's including greek characters following are strings that i want to convert to hex.
Following are different language string which are not working in my current code

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

以下是通过下面提到的javascript函数进行的十六进制转换

Following are hex conversions by javascript function mentioned below

42b41941141f41042041e 3953b33ba3c53ba3bb3bf3c03b13af3b43b53b93b1 e961f673 4772c3192c2b6c3192c217865 4772f6df65

用于将上述字符串转换为十六进制的Javascript函数

Javascript function to convert above string to hex

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

这里没有给出任何转换错误,但在Java端,无法解析使用以下Java代码转换为十六进制的字符串

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

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使用16位unicode字符,因此 charCodeAt 可能返回0到65535之间的任何数字。将其编码为十六进制时,您会得到1到4个字符的字符串,如果简单地将它们连接起来,则另一方无法找出什么字符

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.

您可以通过在编码字符串中添加定界符来解决此问题:

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 Εγκυκλοπαίδεια 维'))

这篇关于将十六进制编码/解码为utf-8字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:56