public static void main(String[] args) {
String str = "大法师123";
System.out.println(msgHex(str));
String hex = "59276CD55E08003100320033";
System.out.println(msg2Hex(hex));
}
/**
* 将汉字转换成16进制
* @param str
* @return
*/
public static String msgHex(String str) {
try {
String msg = new String(str.getBytes("unicode"), "unicode"); // 字符串转换成unicode
String hex = "";
for (int i = 0; i < msg.length(); i++) {
char c = msg.charAt(i);// 找出索引的值
int ch = (int) c;
String chs = Integer.toHexString(ch);// 16进制换算
chs = "000" + chs;
hex = hex + chs.substring(chs.length() - 4);
}
return hex.toUpperCase();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 将16进制转换成汉字
* @param str
* @return
*/
public static String msg2Hex(String hex) {
int len = hex.length() / 4; //每4位截取16进制编码
if (hex.length() % 4 != 0)
return "";
char[] msg = new char[len];
for (int i = 0; i < len; i++) {
String str = hex.substring(4 * i, 4 * i + 4);
int code = Integer.parseInt(str, 16);
msg[i] = (char) code;
}
String msgs = new String(msg);
return msgs;
}