十六进制与字符串的转换

/**
	 * 十六进制转换成utf-8的字符串
	 */
	@Test
	public void test01() {
		try {
			String source = "\\6F\\72\\67\\e6\\9d\\8e";
			String sourceArr[] = source.split("\\\\");
			byte[] byteArr = new byte[sourceArr.length - 1];

			for (int i = 1; i < sourceArr.length; i++) {
				// Integer hexInt = Integer.decode("0x" + sourceArr[i]); // 十六进制数转换成十进制
				Integer hexInt = Integer.parseInt(sourceArr[i],16); 
				byteArr[i - 1] = hexInt.byteValue();
			}
			System.out.println(new String(byteArr, "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 字符串转换成十六进制的数字
	 */
	@Test
	public void test02() {
		String origin = "李";
		StringBuilder sb = new StringBuilder("");
		byte[] bs = origin.getBytes();
		
		for (int i = 0; i < bs.length; i++) {
			sb.append(Integer.toHexString((bs[i] & 0xf0) >> 4));
			sb.append(Integer.toHexString(bs[i] & 0x0f));
			sb.append(' ');
		}
		
		System.out.println(sb.toString().trim());
	}

 

转载于:https://my.oschina.net/u/3524125/blog/1545520

你可能感兴趣的:(十六进制与字符串的转换)