1 /** 2 * byte数组转hex 3 * @param bytes 4 * @return 5 */ 6 public static String byteToHex(byte[] bytes){ 7 String strHex = ""; 8 StringBuilder sb = new StringBuilder(""); 9 for (int n = 0; n < bytes.length; n++) { 10 strHex = Integer.toHexString(bytes[n] & 0xFF); 11 sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示,位数不够,高位补0 12 } 13 return sb.toString().trim(); 14 } 15 16 17 /** 18 * hex转byte数组 19 * @param hex 20 * @return 21 */ 22 public static byte[] hexToByte(String hex){ 23 int m = 0, n = 0; 24 int byteLen = hex.length() / 2; // 每两个字符描述一个字节 25 byte[] ret = new byte[byteLen]; 26 for (int i = 0; i < byteLen; i++) { 27 m = i * 2 + 1; 28 n = m + 1; 29 int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n)); 30 ret[i] = Byte.valueOf((byte)intVal); 31 } 32 return ret; 33 }