2021与蓝度共同重构项目,服务端
zhanzhiqin
2022-08-31 c121143d54615f71d0b87a88ab09da7cfd16d9e4
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
package com.sandu.ximon.admin.manager.iot.rrpc.util;
 
/**
 * @author chenjiantian
 */
public class SupplementUtils {
 
 
    /**
     * 截取指定长度的字符串,不足以0填充前面
     *
     * @param hex      字符串
     * @param totalBit 截取长度
     * @return 截取后的字符串
     */
    public static String suppleZero(String hex, Integer totalBit) {
 
        if (hex.length() > totalBit) {
            return hex.substring(0, totalBit);
        } else if (hex.length() == totalBit) {
            return hex;
        }
        totalBit = totalBit - hex.length();
 
        StringBuilder hexBuilder = new StringBuilder(hex);
        for (int i = 0; i < totalBit; i++) {
            hexBuilder.insert(0, "0");
        }
        hex = hexBuilder.toString();
        return hex;
    }
 
    /**
     * 十进制转16进制,补位0
     *
     * @param index    字符串
     * @param totalBit 截取长度
     * @return 截取后的字符串
     */
    public static String suppleZero(Integer index, Integer totalBit) {
        String format = String.format("%02X", index);
 
        totalBit = totalBit - format.length();
 
        StringBuilder hexBuilder = new StringBuilder(format);
        for (int i = 0; i < totalBit; i++) {
            hexBuilder.insert(0, "0");
        }
        format = hexBuilder.toString();
        return format;
    }
 
    /**
     * 十六进制转换成字节数组
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase(); // 十六进制转大写字母
        int length = hexString.length() / 2; // 获取十六进制的长度,2个字符为一个十六进制
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
 
    /**
     * char转byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
 
 
}