16진수 문자열을 UTF-8로 변환

2662 단어
	public static void convertToUnicode() {
		String originString = "\\e6\\aa\\a2\\e8\\a6\\96\\e6\\aa\\a2  \\e6\\aa\\a2 \\e8\\a6\\96 \\e \\";
		String[] utfStrings= new String[3];
		byte[] UTF8_Encoding = new byte[3];
		int index = 0;

		try {
			for (int i = 0; i < originString.length(); i++) {
				char cur = originString.charAt(i);
				if (cur == '\\' && i + 2 < originString.length()) {
					String str = originString.substring(i, i + 3);
					char a = originString.charAt(++i);
					char b = originString.charAt(++i);
					if (isHexNum(a) && isHexNum(b)) {
						utfStrings[index++] = String.valueOf(str);
					} else {
						System.out.print(str);
						index = 0;
					}
				} else {
					for (int j = 0; j < index; j++) {
						System.out.print(utfStrings[j]);
					}
					System.out.print(cur);
					index = 0;
				}

				if (index == UTF8_Encoding.length) {
					for (int  j = 0; j < utfStrings.length; j++) {
						UTF8_Encoding[j] = (byte) (Integer.parseInt(utfStrings[j].substring(1),
								16));
					}
					System.out.print(new String(UTF8_Encoding, "UTF-8"));
					index = 0;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private static boolean isHexNum(char ch) {
		return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f');
	}
 
 
	public static void convertString() {
		String utf = "\\e6\\aa\\a2\\e8\\a6\\96\\e7\\99\\bc\\e7\\a5\\a8\\e4\\ba\\a4\\e8\\b2\\a8\\e8\\ad\\89\\e6\\98\\8e\\e9\\a0\\85\\e7\\9b\\ae";
		byte[] codes = new byte[3];
		int index = 0;
		char[] chs = new char[2];
		try {
			for (int i = 0; i < utf.length(); i++) {
				char ch = utf.charAt(i);
				if (ch == '\\') {
					if (i + 2 >= utf.length()) {
						System.out.println("wrong input! Please check");
						break;
					}

					chs[0] = utf.charAt(++i);
					chs[1] = utf.charAt(++i);
					if (isNum(chs[0]) && isNum(chs[1])) {
						String s = String.valueOf(chs);
						codes[index++] = (byte) (0xff & Integer.parseInt(s, 16));
					} else {
						System.out.print(ch);
						System.out.print(chs);
					}
				} else {
					System.out.print(ch);
				}

				if (index >= codes.length) {
					index = 0;
					System.out.print(new String(codes, "UTF-8"));
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private static boolean isNum(char a) {
		return (a >= '0' && a <= '9') || (a >= 'a' && a <= 'z');
	}

좋은 웹페이지 즐겨찾기