- 1. 什么是Unicode编码?
- 2. 中文加密[中文字符 -> Unicode字符]
- 3. Unicode解码[Unicode字符 -> 中文字符]
- 4. 测试案例
快速了解什么是Unicode
2. 中文加密[中文字符 -> Unicode字符]
public String unicodeEncode(String string) {
char[] utfBytes = string.toCharArray();
String unicodeBytes = "";
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\u" + hexB;
}
return unicodeBytes;
}
3. Unicode解码[Unicode字符 -> 中文字符]
public String unicodeDecode(String string) {
Pattern pattern = Pattern.compile("(\\u(\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(string);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
string = string.replace(matcher.group(1), ch + "");
}
return string;
}
4. 测试案例
public void test(){
String str = "真香IT";
// 加密 中文 -> Unicode
String unicodeEncode = unicodeEncode(str);
System.out.println(str + " ---> " + unicodeEncode);
// 解密 Unicode -> 中文
String zh_str = unicodeDecode(unicodeEncode);
System.out.println(unicodeEncode + " ---> " + zh_str);
}
欢迎大家留言一起讨论学习!



