将16进制形式的字符串转成UTF-8

本文提供两个实用的Java方法示例,用于将特殊格式的转义字符串转换为Unicode编码的字符。通过逐字符解析并识别十六进制数值,实现从特定格式的字符串到Unicode字符的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	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');
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值