张世豪
昨天 43bd281a47eeac52e649ef79ea25c0dd4d61af7d
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package publicway;
 
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
 
public class HexUtil {
    
    private static final String HEX_CHARS = "0123456789ABCDEF";
    
    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param src 字节数组
     * @return 十六进制字符串,如果输入为空则返回null
     */
    public static String bytesToHexString(byte[] src) {
        return bytesToHexString(src, 0, src != null ? src.length : 0);
    }
    
    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param src 字节数组
     * @param len 要转换的长度
     * @return 十六进制字符串,如果输入为空则返回null
     */
    public static String bytesToHexString(byte[] src, int len) {
        return bytesToHexString(src, 0, len);
    }
    
    /**
     * 将字节数组指定范围转换为十六进制字符串
     *
     * @param src 字节数组
     * @param start 起始位置
     * @param end 结束位置
     * @return 十六进制字符串,如果输入为空则返回null
     */
    public static String bytesToHexString(byte[] src, int start, int end) {
        if (src == null || src.length == 0) {
            return null;
        }
        
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = start; i < end && i < src.length; i++) {
            int v = src[i] & 0xFF;
            stringBuilder.append(HEX_CHARS.charAt(v >>> 4));
            stringBuilder.append(HEX_CHARS.charAt(v & 0x0F));
        }
        return stringBuilder.toString();
    }
    
    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hexString 十六进制字符串
     * @return 字节数组,如果输入为空则返回null
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.isEmpty()) {
            return null;
        }
        
        String normalizedHex = hexString.toUpperCase().replaceAll("[^0-9A-F]", "");
        if (normalizedHex.length() % 2 != 0) {
            throw new IllegalArgumentException("十六进制字符串长度必须为偶数");
        }
        
        int length = normalizedHex.length() / 2;
        byte[] result = new byte[length];
        
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            int high = charToByte(normalizedHex.charAt(pos));
            int low = charToByte(normalizedHex.charAt(pos + 1));
            result[i] = (byte) ((high << 4) | low);
        }
        return result;
    }
    
    /**
     * 字符转换为字节
     *
     * @param c 字符
     * @return 字节值
     */
    private static byte charToByte(char c) {
        return (byte) HEX_CHARS.indexOf(c);
    }
    
    /**
     * 整数转换为4字节数组(大端序)
     *
     * @param num 整数
     * @return 4字节数组
     */
    public static byte[] intToBytes(int num) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            bytes[i] = (byte) (num >>> (24 - i * 8));
        }
        return bytes;
    }
    
    /**
     * 字符串转换为十六进制字符串
     *
     * @param str 输入字符串
     * @return 十六进制字符串
     */
    public static String strToHexStr(String str) {
        if (str == null) return "";
        
        StringBuilder sb = new StringBuilder();
        byte[] bytes = str.getBytes();
        for (byte b : bytes) {
            sb.append(HEX_CHARS.charAt((b & 0xF0) >> 4));
            sb.append(HEX_CHARS.charAt(b & 0x0F));
        }
        return sb.toString();
    }
    
    /**
     * 计算Modbus CRC-16校验码(返回大写十六进制字符串)
     *
     * @param data 输入数据
     * @return 4位大写的十六进制CRC字符串
     */
    public static String calculate(byte[] data) {
        int crc = 0xFFFF;
        for (byte b : data) {
            crc ^= b & 0xFF;
            for (int i = 0; i < 8; i++) {
                if ((crc & 1) == 1) {
                    crc = (crc >>> 1) ^ 0xA001;
                } else {
                    crc = crc >>> 1;
                }
            }
        }
        // 使用大写格式,确保4位长度,不足补零
        return String.format("%04X", crc);
    }
    
    /**
     * BCD码转为字符串
     *
     * @param bytes BCD码字节数组
     * @return 十进制字符串
     */
    public static String bcdToStr(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        
        StringBuilder temp = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            temp.append((b & 0xF0) >>> 4);
            temp.append(b & 0x0F);
        }
        
        // 去除前导零
        String result = temp.toString();
        return result.startsWith("0") ? result.substring(1) : result;
    }
    
    /**
     * 字符串转为BCD码
     *
     * @param asc 十进制字符串
     * @return BCD码字节数组
     */
    public static byte[] strToBcd(String asc) {
        if (asc == null || asc.isEmpty()) {
            return new byte[0];
        }
        
        // 确保长度为偶数
        String normalized = asc.length() % 2 != 0 ? "0" + asc : asc;
        byte[] result = new byte[normalized.length() / 2];
        
        for (int i = 0; i < result.length; i++) {
            char highChar = normalized.charAt(2 * i);
            char lowChar = normalized.charAt(2 * i + 1);
            
            int high = charToBcdValue(highChar);
            int low = charToBcdValue(lowChar);
            
            result[i] = (byte) ((high << 4) | low);
        }
        return result;
    }
    
    private static int charToBcdValue(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'a' && c <= 'f') {
            return c - 'a' + 10;
        } else if (c >= 'A' && c <= 'F') {
            return c - 'A' + 10;
        } else {
            throw new IllegalArgumentException("无效的BCD字符: " + c);
        }
    }
    
    /**
     * 反转字节数组
     *
     * @param data 字节数组
     * @param len 要反转的长度
     */
    public static void reverse(byte[] data, int len) {
        if (data == null || len <= 1) return;
        
        for (int i = 0; i < len / 2; i++) {
            byte temp = data[i];
            data[i] = data[len - 1 - i];
            data[len - 1 - i] = temp;
        }
    }
    
    /**
     * 字节数组转换为字符串(遇到0x00终止)
     *
     * @param data 字节数组
     * @return 字符串
     */
    public static String bytesToString(byte[] data) {
        if (data == null || data.length == 0) {
            return "";
        }
        
        int length = 0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == 0) {
                length = i;
                break;
            }
            length = data.length;
        }
        
        return new String(data, 0, length);
    }
    
    /**
     * 获取异常的堆栈跟踪信息
     *
     * @param e 异常
     * @return 格式化的异常信息
     */
    public static String getExceptionTrace(Exception e) {
        if (e == null) return "";
        
        StringBuilder message = new StringBuilder("异常消息: " + e.getMessage());
        
        StackTraceElement[] stackTrace = e.getStackTrace();
        if (stackTrace != null && stackTrace.length > 0) {
            StackTraceElement firstElement = stackTrace[0];
            message.append(" 报错位置: ")
                  .append(firstElement.getClassName()).append(".")
                  .append(firstElement.getMethodName()).append("(")
                  .append(firstElement.getFileName()).append(":")
                  .append(firstElement.getLineNumber()).append(")");
        }
        return message.toString();
    }
    
    // 以下方法保持原有功能,但建议使用Java标准库替代
    // 由于时间关系,这里只优化主要方法
    
    /**
     * 字节数组(去掉后面的0)转Unicode字符串
     * 注意:此方法逻辑较复杂,建议在实际使用中验证
     */
    public static String bytesToUnicodeString(byte[] src) {
        // 保持原有实现,但建议重构
        if (src == null || src.length == 0) {
            return "";
        }
        
        int strlen = 0;
        for (int j = src.length - 1; j >= 0; j--) {
            if (src[j] != 0) {
                strlen = j + 1;
                break;
            }
        }
        
        if (strlen == 0) {
            return "";
        }
        
        // 确保长度为偶数
        if (strlen % 2 != 0) {
            strlen++;
        }
        
        byte[] strData = Arrays.copyOfRange(src, 0, strlen);
        try {
            // 交换字节序
            swapBytes(strData);
            return new String(strData, "UNICODE");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("不支持的编码: UNICODE", e);
        }
    }
    
    private static void swapBytes(byte[] data) {
        for (int i = 0; i < data.length / 2; i++) {
            byte temp = data[2 * i];
            data[2 * i] = data[2 * i + 1];
            data[2 * i + 1] = temp;
        }
    }
}