hex字符串、byte[]數組互相轉換

 1     //byte[]轉hex字符串
 2     public static String bytes2HexString(byte[] array) {  3         StringBuilder builder = new StringBuilder();  4 
 5         for (byte b : array) {  6             String hex = Integer.toHexString(b & 0xFF);  7             if (hex.length() == 1) {  8                 hex = '0' + hex;  9  } 10  builder.append(hex); 11  } 12 
13         return builder.toString().toUpperCase(); 14  } 15 
16     //hex字符串轉byte[]數組
17     public static byte[] hexToByteArray(byte mode, String hex) 18  { 19         hex = hex.replaceAll("\\s*", ""); //去除空格等字符
20         int len = hex.length(); //字符串長度
21         hex = len % 2 == 0 ? hex : hex + "N"; //保持長度爲偶數//或減一位 22         //從新計算長度
23         len = hex.length(); 24         int bts_len = (len / 2 + 3); //總字節數,增長3字節
25         byte[] data = new byte[bts_len]; 26         data[0] = DATA_FLAG; 27         data[1] = mode; //模式標誌
28         for (int i = 0; i < len; i += 2) 29  { 30             data[i / 2 + 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) 31                     + Character.digit(hex.charAt(i + 1), 16)); 32  } 33         data[bts_len - 1] = DATA_FLAG; 34 
35         //輸出查看
36  Log.d(TAG, bytes2HexString(data)); 37 
38         return data; 39     }
相關文章
相關標籤/搜索