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; } }