首先,byte數(shù)組轉(zhuǎn)成16進(jìn)制字符串:
/** * byte數(shù)組轉(zhuǎn)成字符串 * * @param bytes 數(shù)組 * @param isCaptial 使用大寫還是小寫表示 * @return 轉(zhuǎn)換后的字符串 */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進(jìn)制字符表示當(dāng)前的byte數(shù)據(jù),X或者x表示16進(jìn)制字符串 s.append(String.format("%02X", bytes[i])); } else { s.append(String.format("%02x", bytes[i])); } } return s.toString(); }然后,將16進(jìn)制字符串轉(zhuǎn)成byte數(shù)組:
public static byte[] hexStrToBytes(String hex) { if (null == hex || hex.equals("")) { return null; } int strLength = hex.length();//獲取16進(jìn)制字符串長(zhǎng)度 int length = strLength / 2; //獲取字節(jié)長(zhǎng)度 char[] hexChars;//用來存放字符串轉(zhuǎn)換成的字符數(shù)組 if (length * 2 < strLength) { // strLength is odd, add '0' length += 1; hexChars = ("0" + hex).toCharArray(); } else { hexChars = hex.toCharArray(); } byte[] bytes = new byte[length];//用來存放最終組成的數(shù)組 for (int i = 0; i < length; i++) { int pos = i * 2; //組成1字節(jié)的數(shù)據(jù)。因?yàn)槭切枰獌蓚€(gè)字符組成一個(gè)字節(jié)的數(shù)據(jù),這就需要第一個(gè)字符向左移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; } }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注