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 }