dangsn
2024-06-06 8c8c59c1f2005fa3ca89ac2117ca1a3c0c618913
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
package com.vci.web.util;
 
/**
 * 数据类型转换工具类
 *
 * @author Chill
 */
public class DatatypeConverterUtil {
 
    /**
     * hex文本转换为二进制
     *
     * @param hexStr hex文本
     * @return byte[]
     */
    public static byte[] parseHexBinary(String hexStr) {
        final int len = hexStr.length();
 
        if (len % 2 != 0) {
            throw new IllegalArgumentException("hexBinary needs to be even-length: " + hexStr);
        }
 
        byte[] out = new byte[len / 2];
 
        for (int i = 0; i < len; i += 2) {
            int h = hexToBin(hexStr.charAt(i));
            int l = hexToBin(hexStr.charAt(i + 1));
            if (h == -1 || l == -1) {
                throw new IllegalArgumentException("contains illegal character for hexBinary: " + hexStr);
            }
 
            out[i / 2] = (byte) (h * 16 + l);
        }
 
        return out;
    }
 
    /**
     * hex文本转换为int
     *
     * @param ch hex文本
     * @return int
     */
    private static int hexToBin(char ch) {
        if ('0' <= ch && ch <= '9') {
            return ch - '0';
        }
        if ('A' <= ch && ch <= 'F') {
            return ch - 'A' + 10;
        }
        if ('a' <= ch && ch <= 'f') {
            return ch - 'a' + 10;
        }
        return -1;
    }
 
}