1.將byte[]數組轉換成16進制字符
/** * 將byte[]數組轉換成16進制字符。一個byte生成兩個字符,長度對應1:2 * @param bytes,輸入byte[]數組 * @return 16進制字符 */ public static String byte2Hex(byte[] bytes) { if (bytes == null) { return null; } StringBuilder builder = new StringBuilder(); // 遍歷byte[]數組,將每個byte數字轉換成16進制字符,再拼接起來成字符串 for (int i = 0; i < bytes.length; i++) { // 每個byte轉換成16進制字符時,bytes[i] & 0xff如果高位是0,輸出將會去掉,所以+0x100(在更高位加1),再截取后兩位字符 builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); } return builder.toString(); }
2.將16進制字符轉換成byte[]數組
/** * 將16進制字符轉換成byte[]數組。與byte2Hex功能相反。 * @param string 16進制字符串 * @return byte[]數組 */ public static byte[] hex2Byte(String string) { if (string == null || string.length() < 1) { return null; } // 因為一個byte生成兩個字符,長度對應1:2,所以byte[]數組長度是字符串長度一半 byte[] bytes = new byte[string.length() / 2]; // 遍歷byte[]數組,遍歷次數是字符串長度一半 for (int i = 0; i < string.length() / 2; i++) { // 截取沒兩個字符的前一個,將其轉為int數值 int high = Integer.parseInt(string.substring(i * 2, i * 2 + 1), 16); // 截取沒兩個字符的后一個,將其轉為int數值 int low = Integer.parseInt(string.substring(i * 2 + 1, i * 2 + 2), 16); // 高位字符對應的int值*16+低位的int值,強轉成byte數值即可 // 如dd,高位13*16+低位13=221(強轉成byte二進制11011101,對應十進制-35) bytes[i] = (byte) (high * 16 + low); } return bytes; }