感謝 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"));
}
}
這里有個很惡心的問題。
只能轉換成純中文的, 也就是說如果待轉換的字符串中,存在正常的符號數字字母時,會報錯
