java中byte[] 和16进制字符串互转


//将byte[]转换为16进制字符串

public static String byte2hex(byte[] b) {
    StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
//将16进制字符串转换为byte[]
public static byte[] toBytes(String str) {
if(str == null || str.trim().equals("")) {
return new byte[0];
} byte[] bytes = new byte[str.length() / 2];
for(int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
} return bytes;
}

参考:https://blog.csdn.net/worm0527/article/details/69939307
上一篇:JavaScript中字符串与16进制之间的转换


下一篇:Codeforces Round #411 (Div. 2) 【ABCDE】