随笔 - 38,  文章 - 1,  评论 - 2,  阅读 - 13605
复制代码
 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   yang希军  阅读(445)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示