将汉字转换成UniCode编码
public static String gbEncoding(final String gbString) { //gbString = "你好"
char[] utfBytes = gbString.toCharArray(); //utfBytes = [你, 好]
String unicodeBytes = "";
//循环读取每一个汉字,将每个汉字转换成16进制编码字符串
for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
String hexB = Integer.toHexString(utfBytes[byteIndex]); //转换为16进制整型字符串
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB; //在16进制编码前加上\u
}
System.out.println("unicodeBytes is: " + unicodeBytes);
return unicodeBytes;
}
将UniCode编码转换成汉字
public static String decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("\\u", start + 2);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 2, dataStr.length());
} else {
charStr = dataStr.substring(start + 2, end);
}
char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
buffer.append(new Character(letter).toString());
start = end;
}
return buffer.toString();
}