1 public class HexConverUtils {
 2 
 3     /**
 4      * 16进制字符集
 5      */
 6     private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5',
 7             '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 8 
 9     /**
10      * 将字节数组转换成16进制字符串
11      *
12      * @param bytes 目标字节数组
13      * @return 转换结果
14      */
15     public static String bytesToHex(byte bytes[]) {
16         return bytesToHex(bytes, 0, bytes.length);
17     }
18 
19     /**
20      * 将字节数组中指定区间的子数组转换成16进制字符串
21      *
22      * @param bytes 目标字节数组
23      * @param start 起始位置(包括该位置)
24      * @param end   结束位置(不包括该位置)
25      * @return 转换结果
26      */
27     public static String bytesToHex(byte bytes[], int start, int end) {
28         StringBuilder sb = new StringBuilder();
29         for (int i = start; i < start + end; i++) {
30             sb.append(byteToHex(bytes[i]));
31         }
32         return sb.toString();
33     }
34 
35     /**
36      * 将单个字节码转换成16进制字符串
37      *
38      * @param bt 目标字节
39      * @return 转换结果
40      */
41     public static String byteToHex(byte bt) {
42         return HEX_DIGITS[(bt & 0xf0) >> 4] + "" + HEX_DIGITS[bt & 0xf];
43     }
44 
45 
46     /**
47      * 将16进制字符串转换成字节数组
48      *
49      * @param hexString 16进制字符串
50      * @return byte[] 字节数组
51      */
52     public static byte[] hexToBytes(String hexString) {
53         if (hexString == null || hexString.equals("")) {
54             return null;
55         }
56         hexString = hexString.toUpperCase();
57         int length = hexString.length() / 2;
58         char[] hexChars = hexString.toCharArray();
59         byte[] d = new byte[length];
60         for (int i = 0; i < length; i++) {
61             int pos = i * 2;
62             d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
63         }
64         return d;
65     }
66 
67 
68     /**
69      * 将字符转换成字节
70      *
71      * @param c 字符
72      * @return byte 字节
73      */
74     private static byte charToByte(char c) {
75         return (byte) "0123456789ABCDEF".indexOf(c);
76     }
77 }

 

posted on 2023-04-09 09:47  yang希军  阅读(482)  评论(0)    收藏  举报