unicode编码规则
unicode码对每一个字符用4位16进制数表示。具体规则是:将一个字符(char)的高8位与低8位分别取出,转化为16进制数,如果转化的16进制数的长度不足2位,则在其后补0,然后将高、低8位转成的16进制字符串拼接起来并在前面补上"\u" 即可。
版权声明:本文为博主原创文章,未经博主允许不得转载。原文地址:https://www.cnblogs.com/poterliu/p/9579918.html 联系邮箱:[email protected] 联系微信:poterliu 或者扫二维码 |
转换工具实现代码:
/** * 字符串与unicode的相互转换工具类 * @author poterliu */ public class UnicodeConvertUtil { /** * 将字符串转成unicode * @param str 待转字符串 * @return unicode字符串 */ public static String convert(String str) { str = (str == null ? "" : str); String tmp; StringBuffer sb = new StringBuffer(1000); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("\\u"); j = (c >>>8); //取出高8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); j = (c & 0xFF); //取出低8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); } return (new String(sb)); } /** * 将unicode转成字符串 * @param str 待转字符串 * @return 普通字符串 */ public static String revert(String str) { str = (str == null ? "" : str); if (str.indexOf("\\u") == -1)//如果不是unicode码则原样返回 return str; StringBuffer sb = new StringBuffer(1000); for (int i = 0; i < str.length() - 6;) { String strTemp = str.substring(i, i + 6); String value = strTemp.substring(2); int c = 0; for (int j = 0; j < value.length(); j++) { char tempChar = value.charAt(j); int t = 0; switch (tempChar) { case ‘a‘: t = 10; break; case ‘b‘: t = 11; break; case ‘c‘: t = 12; break; case ‘d‘: t = 13; break; case ‘e‘: t = 14; break; case ‘f‘: t = 15; break; default: t = tempChar - 48; break; } c += t * ((int) Math.pow(16, (value.length() - j - 1))); } sb.append((char) c); i = i + 6; } return sb.toString(); } }
参考:
https://blog.csdn.net/yanqun1017/article/details/60955807
全文完
:)
原文地址:https://www.cnblogs.com/poterliu/p/9579918.html
时间: 2024-11-13 06:31:14