public class UnicodeUtils {
public static void main(String[] args) {
String s = "我爱你s";
System.out.println(getUnicode(s)); // \u6211\u7231\u4f60\u0073
}
/**
* 获取字符串的Unicode,即将字符串转化成Unicode
* @param str
* @return String
* @throws
* @author liaowenxiong
* @date 2022/12/17 15:57
*/
public static String getUnicode(String str) {
String unicode = "";
if (str != null) {
for (char c : str.toCharArray()) {
if (c > 255) {
unicode += "\\u" + Integer.toHexString((int) c);
} else {
unicode += "\\u00" + Integer.toHexString((int) c);
}
}
}
return unicode;
}
}
注:Unicode 编码,是用 2 个字节要表示一个字符,而小于等于 255 的字符都是欧美的字符,1 个字节就可以表示了,它们的范围是 00000000~11111111,可以表示 256 个字符。Integer.toHexString(c)
,如果 c 的编码(其实就是在 Unicode 字符集中的码位)小于 255,那么返回的十六进制数就只要两位(十六进制的两位对应二进制的八位,就是一个字节),所以前面补两个 0,让显示的长度保持一致