字符串和十六进制转换

  public static String hex2Str(String hexString) {
		String result = "";
		byte[] bytes = new byte[hexString.length() / 2];

		try {
			for (int i = 0; i < hexString.length(); i += 2) {
				bytes[i / 2] = Integer.decode(
						"0x" + hexString.substring(i, i + 2)).byteValue();
			}
			result = new String(bytes, 0, bytes.length, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


	public static String str2Hex(String str) {
		String result = "";
		String tmpStr;
		try {
			byte[] bytes = str.getBytes("UTF-8");
			for (int i = 0; i < bytes.length; i++) {
				tmpStr = Integer.toHexString(bytes[i]).toUpperCase();
				result += tmpStr.length() == 1 ? "0" + tmpStr : tmpStr;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

 

你可能感兴趣的:(进制转换)