今天用到ASCLL碼和字符串之間的轉化,在此記錄分享一下。
首先提供一個方法,將字符串轉換成爲16進制的ASCLL碼字符串,可以包含漢字、數字、標點符號等
public static String str2HexStr(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s1 = Integer.toHexString(ch);
str += s1 + " ";
}
return str;
}
然後提供一個方法,將16進制的ASCLL碼字符串轉換成爲string類型字符串,可以包含漢字、數字、標點符號等
public static String hexStr2Str(String s) {
String[] asclls = s.split(" ");
byte[] tmp = new byte[1];
String result = "";
for (int i = 0; i < asclls.length; i++) {
try {
if (Integer.valueOf(asclls[i], 16).intValue() > 255) {
result += (char) Integer.valueOf(asclls[i], 16).intValue();
} else {
tmp[0] = (byte) (0xff & Integer.parseInt(asclls[i], 16));
result += new String(tmp, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
最後測試一下
String hexStr = str2HexStr("3、2、1,I love you, 中國!");
System.out.println(hexStr);
System.out.println(hexStr2Str(hexStr));
結果