//16进制字符串转化为字节
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = b.length-1; i >=0; i--) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}
private static int parse(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
//转换为16进制字符串
public static String hexString(String str) {
String ret = "";
byte[] b;
try {
b = str.getBytes("GB2312");
for (int i = b.length - 1; i >= 0; i--) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ret;
}
public static void main(String[] args) throws Exception {
String str = hexString("好啊tianta了");
System.out.println(str);
byte[] b = HexString2Bytes(str);
String s=new String(b,"GB2312");
System.out.println(s);
}
字符转换为16进制字符串以及转换回来的方法
最新推荐文章于 2022-06-30 15:27:37 发布