czt
2024-07-13 b030109e665301e7edd6ad0fe5c832ee10fe39b4
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
package com.ld.igds.protocol.es.dlt645.util;
 
/**
 * 工具类
 *
 * @author czt
 */
public class Dlt645Utils {
 
 
    public static String MSG_START = "FEFEFEFE"; //起始符
    public static String MSG_END = "16"; //结尾符
 
    public static void main(String[] args) {
        String s = makeCheck("6857141222000068110433333433");
        System.out.println(s);
    }
 
    /**
     * 将6个字节的地址域,每字节2位 BCD码,转换为12位10进制数
     */
    public static String addrToString(String str) {
        byte[] bytes = stringToBytes(str);
        return String.format("%02x%02x%02x%02x%02x%02x", bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
    }
 
    /**
     * DLT645校验码
     */
    public static String makeCheck(String data) {
 
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        /**
         * 用256求余最大是255,即16进制的FF
         */
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度,补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex.toUpperCase();
    }
 
    /**
     * 将String类型转换成byte数组
     */
    public static byte[] stringToBytes(String str) {
        if (str == null || str.equals("")) {
            return null;
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }
 
    /**
     * 解析返回的具体数据
     */
    public static Double parseData(String dataStr) {
        byte[] data = stringToBytes(dataStr);
        // 每个字节-33H处理
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (data[i] - 0x33);
        }
        StringBuilder str = new StringBuilder();
        // BCD码转换成10进制
        for (byte b : data) {
            str.insert(0, String.format("%02x", b));
        }
        return Double.parseDouble(str.toString()) * 0.01;
    }
 
}