13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
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
package com.ruoyi.fuzhou.utils.hj1239;
 
import java.nio.charset.StandardCharsets;
 
/**
 * 数据封装
 */
public class ProtocolDataEncoder {
    public static final byte START_FLAG = 0x01;
    public static final byte END_FLAG = 0x02;
 
    public static byte[] encodeData(String data) {
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
        byte checksum = calculateChecksum(dataBytes);
        byte[] frame = new byte[2 + dataBytes.length + 1];
        frame[0] = START_FLAG;
        System.arraycopy(dataBytes, 0, frame, 1, dataBytes.length);
        frame[frame.length - 2] = checksum;
        frame[frame.length - 1] = END_FLAG;
        return frame;
    }
 
    public static byte calculateChecksum(byte[] data) {
        byte sum = 0;
        for (byte b : data) {
            sum += b;
        }
        return sum;
    }
}