我在编码和解码字符串时遇到问题。如果我将字符串 a 编码为 b 那么 b 到 c 意味着它工作正常。如果我转换 finalstring 意味着我得到了一些额外的字符。请查看我的输出以了解您在输出末尾获得额外字符的说明。
这是我的代码。
public class DoubleByteReverse {
public static void main(String args[]) {
try{
String a = new String("基本形");
System.out.println("a value "+a);
String b=new String(a.getBytes("Cp939"), "Cp500");
System.out.println("b value "+b);
String c=new String(b.getBytes("Cp500"), "Cp939");
System.out.println("c value "+c);
String g = new String("ã1áÃã°");
String x = "0x0E";
byte[] bytes = hexStringToByteArray(x);
String st = new String(bytes,"Cp500");
//System.out.println(st);
String y = "0x0F";
byte[] bytes1 = hexStringToByteArray(y);
String en = new String(bytes1,"Cp500");
//System.out.println(en);
String finalstring =new String(st+g+en);
System.out.println("whole string "+finalstring);
String output=new String(finalstring.getBytes("Cp500"),"Cp939");
System.out.println("output "+output);
}
catch (UnsupportedEncodingException e){}
}
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l/2];
for (int i = 0; i < l; i += 2) {
data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
}
return data;
}
}
输出:
a value 基本形
b value ã1áÃã°
c value 基本形
whole string ã1áÃã°
output 基本形�
最佳答案
看起来你在 hexStringToByteArray
中做的事情并没有正常工作,但是如果你改变 finalstring
的值,这个值 new String("\u000E"+ g + "\u000F")
它按预期工作。
关于java - 编码和解码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477652/