Unicode字符串轉換

	private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
	//字符串轉unicode
	public static String str2Unicode(String message) {
		if (message == null || message.isEmpty()) {
			return message;
		}
		StringBuilder unicodeCharBuilder = new StringBuilder();
		int length = message.length();
		for (int index=0; index < length; index++) {
			char indexChar = message.charAt(index);
			unicodeCharBuilder.append("\\u");
			unicodeCharBuilder.append(DIGITS_LOWER[(indexChar >> 12) & 15]);
			unicodeCharBuilder.append(DIGITS_LOWER[(indexChar >> 8) & 15]);
			unicodeCharBuilder.append(DIGITS_LOWER[(indexChar >> 4) & 15]);
			unicodeCharBuilder.append(DIGITS_LOWER[indexChar & 15]);
		}
		return unicodeCharBuilder.toString();
	}
   //unicode轉字符串
	public static String unicode2Str(String unicode) {
		if (unicode == null || unicode.isEmpty()) {
			return unicode;
		}
		int length = unicode.length();
		StringBuilder builder = new StringBuilder();
		int index = -1;
		int pos = 0;
		while ((index = unicode.indexOf("\\u", pos)) != -1) {
			builder.append(unicode.substring(pos, index));
			try {
				builder.append((char)Integer.valueOf(unicode.substring(index+2, index+6), 16).intValue());
				pos = index + 6;
			} catch (Exception e) {
				builder.append(unicode.substring(index, index+2));
				pos = index+2;
			}
		}
		if (pos != length) {
			builder.append(unicode.substring(pos, length));
		}
		return builder.toString();
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章