感谢 http://my.oschina.net/leejun2005/blog/106791
代码如下:
public class App { public static String str2Hex(String str) throws UnsupportedEncodingException { String hexRaw = String.format("%x", new BigInteger(1, str.getBytes("UTF-8"))); char[] hexRawArr = hexRaw.toCharArray(); StringBuilder hexFmtStr = new StringBuilder(); final String SEP = "\x"; for (int i = 0; i < hexRawArr.length; i++) { hexFmtStr.append(SEP).append(hexRawArr[i]).append(hexRawArr[++i]); } return hexFmtStr.toString(); } public static String hex2Str(String str) throws UnsupportedEncodingException { String strArr[] = str.split("\\"); // 分割拿到形如 xE9 的16进制数据 byte[] byteArr = new byte[strArr.length - 1]; for (int i = 1; i < strArr.length; i++) { Integer hexInt = Integer.decode("0" + strArr[i]); byteArr[i - 1] = hexInt.byteValue(); } return new String(byteArr, "UTF-8"); } public static void main(String[] args) throws UnsupportedEncodingException { System.out.println(str2Hex("中国1a23")); System.out.println(hex2Str(str2Hex("中国1a23"))); System.out.println(hex2Str("\xE9\xA6\x96\xE9\xA1\xB5\xE6\x8E\xA8\xE8\x8D\x90")); } }
这里有个很恶心的问题。
只能转换成纯中文的, 也就是说如果待转换的字符串中,存在正常的符号数字字母时,会报错