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

在开发Web应用时,遇到将包含希腊字符的UTF-8字符串转换为16进制的问题。JavaScript的编码函数能成功转换,但Java解析时出现异常。原因是JavaScript的charCodeAt返回16位Unicode值,导致1到4个字符的16进制串。解决方案是在JavaScript编码时使用分隔符,如 `-`,以便Java能正确解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Following are hex conversions by javascript function mentioned below

42b41941141f41042041e 3953b33ba3c53ba3bb3bf3c03b13af3b43b53b93b1 e961f673 4772c3192c2b6c3192c217865 4772f6df65

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;

}

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

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值