xiaoyong931011
2023-10-11 63a12d1eaaea08d7573e2788156adb7976a8a32d
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
package cc.mrbird.febs.pay.util;
 
import cc.mrbird.febs.common.exception.JPException;
import cc.mrbird.febs.pay.model.CommonConst;
 
/**
 * 16进制工具类
 * @author chenyf
 * @date 2018-12-15
 */
public class HEXUtil {
    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
    private static final char[] DIGITS_UPPER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 
 
    public static String encode(String str){
        try{
            return encode(str.getBytes(CommonConst.ENCODING_UTF_8), true);
        }catch (Exception e){
            throw new JPException("16进制转换失败", e);
        }
    }
 
    public static String encode(byte[] data, final boolean toUpperCase){
        return bytes2Hex(data, toUpperCase ? DIGITS_UPPER : DIGITS_LOWER);
    }
 
    public static String decode(String str){
        try{
            byte[] date = hex2Bytes(str);
            return new String(date, CommonConst.ENCODING_UTF_8);
        }catch (Exception e){
            throw new JPException("16进制转换失败", e);
        }
    }
 
    private static String bytes2Hex(final byte[] data, final char[] toDigits) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return new String(out);
    }
 
    private static byte[] hex2Bytes(final String data) throws Exception {
        final int len = data.length();
 
        if ((len & 0x01) != 0) {
            throw new Exception("Odd number of characters.");
        }
 
        final byte[] out = new byte[len >> 1];
 
        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data.charAt(j), j) << 4;
            j++;
            f = f | toDigit(data.charAt(j), j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }
        return out;
    }
 
    /**
     * 16转化为数字
     * @param ch 16进制
     * @param index 索引
     * @return 转化结果
     * @throws Exception 转化失败异常
     */
    private static int toDigit(final char ch, final int index) throws Exception {
        final int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
        }
        return digit;
    }
}