java中 Hex(十六进制)和byte[]相互转换
1.Hex转成byte[]
/** * hex转byte数组 * @param hex * @return */ public static byte[] hexToByte(String hex){ int m = 0, n = 0; int byteLen = hex.length() / 2; // 每两个字符描述一个字节 byte[] ret = new byte[byteLen]; for (int i = 0; i < byteLen; i++) { m = i * 2 + 1; n = m + 1; int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n)); ret[i] = Byte.valueOf((byte)intVal); } return ret; }
2.byte[]转Hex
/** * byte数组转hex * @param bytes * @return */ public static String byteToHex(byte[] bytes){ String strHex = ""; StringBuilder sb = new StringBuilder(""); for (int n = 0; n < bytes.length; n++) { strHex = Integer.toHexString(bytes[n] & 0xFF); sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示,位数不够,高位补0 } return sb.toString().trim(); }