public void testApp() throws Exception
{
//十六进制编码转中文字符串
String string = "C2ACD0E3cbd5343232373234313836323230323033313833";
String result = stringToGbk(string);
System.out.println(result);
//中文字符串转十六进制编码字符串
String a="李斯";
byte[] b=a.getBytes("GB2312");
String hexStr = bytesToHexFun1(b);
System.out.println(hexStr);
}
//将gbk编码转换成汉字
public String stringToGbk(String string) throws Exception
{
byte[] bytes = new byte[string.length() / 2];
for(int i = 0; i < bytes.length; i ++){
byte high = Byte.parseByte(string.substring(i * 2, i * 2 + 1), 16);
byte low = Byte.parseByte(string.substring(i * 2 + 1, i * 2 + 2), 16);
bytes[i] = (byte) (high << 4 | low);
}
String result = new String(bytes, "gbk");
return result;
}
//将byte数组转成16进制字符串
public static String bytesToHexFun1(byte[] bytes) {
char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
// 一个byte为8位,可用两个十六进制位标识
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
for(byte b : bytes) { // 使用除与取余进行转换
if(b < 0) {
a = 256 + b;
} else {
a = b;
}
buf[index++] = HEX_CHAR[a / 16];
buf[index++] = HEX_CHAR[a % 16];
}
return new String(buf);
}
参考资料:
1、http://doc.chacuo.net/gb2312
2、https://bbs.csdn.net/topics/390283856
3、https://zhidao.baidu.com/question/1110700468326328739.html