首先,byte數組轉成16進制字符串:
/** * byte數組轉成字符串 * * @param bytes 數組 * @param isCaptial 使用大寫還是小寫表示 * @return 轉換后的字符串 */public static String bytesToHexStr(byte[] bytes, boolean isCaptial) { if (null == bytes || bytes.length <= 0) { return null; } StringBuilder s = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { if (isCaptial) { //02表示使用2位16進制字符表示當前的byte數據,X或者x表示16進制字符串 s.append(String.format("%02X", bytes[i])); } else { s.append(String.format("%02x", bytes[i])); } } return s.toString(); }然后,將16進制字符串轉成byte數組:
public static byte[] hexStrToBytes(String hex) { if (null == hex || hex.equals("")) { return null; } int strLength = hex.length();//獲取16進制字符串長度 int length = strLength / 2; //獲取字節長度 char[] hexChars;//用來存放字符串轉換成的字符數組 if (length * 2 < strLength) { // strLength is odd, add '0' length += 1; hexChars = ("0" + hex).toCharArray(); } else { hexChars = hex.toCharArray(); } byte[] bytes = new byte[length];//用來存放最終組成的數組 for (int i = 0; i < length; i++) { int pos = i * 2; //組成1字節的數據。因為是需要兩個字符組成一個字節的數據,這就需要第一個字符向左移4位。 bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return bytes; }public static byte charToByte(char c) { byte result = (byte) "0123456789abcdef".indexOf(c); if (result == -1) { return (byte) "0123456789ABCDEF".indexOf(c); } else { return result; } }新聞熱點
疑難解答