[英]Encoding and Decoding string
I have an issue while encoding and decoding string.我在编码和解码字符串时遇到问题。 If i encode string a to b then b to c means it works fine.如果我将字符串 a 编码为 b 那么 b 到 c 意味着它工作正常。 If I convert finalstring means I got some extra characters.如果我转换 finalstring 意味着我得到了一些额外的字符。 Please view my output for your clarifications am getting extra character at the end in output.请查看我的输出以了解您在输出的末尾获得额外字符的说明。
Here is my code.这是我的代码。
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;
}
}
Output:输出:
a value 基本形
b value ã1áÃã°
c value 基本形
whole string ã1áÃã°
output 基本形�
似乎您在hexStringToByteArray
中hexStringToByteArray
的工作无法正常工作,但是如果您为此值更改finalstring
的值new String("\" + g + "\")
它会按预期工作。
Try using :尝试使用:
Import this > import javax.xml.bind.DatatypeConverter;
导入这个 > import javax.xml.bind.DatatypeConverter;
DatatypeConverter.printHexBinary(bytes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.