endian11
2020-09-16 cab2ea881e5711d16cf0003e8b00489a2c766365
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 safeluck.drive.evaluation.platformMessage.utils;
 
 
import com.safeluck.aykj.utils.ArrayUtils;
 
/**
 * Created by zw on 2017/7/8.
 * 蓝牙协议转义
 */
 
public class MessageEscaper {
 
    public  byte[] escape(byte[] source_bytes)
    {
        byte[] return_bytes = new byte[source_bytes.length*2];
 
        int size = source_bytes.length;
        int pos = 0;
        for (int i = 0; i < size; i++)
        {
            if (i == 0||i==size-1)
            {
                return_bytes[pos++] = source_bytes[i];
                continue;
            }
            if (source_bytes[i] == 0x7d)
            {
                return_bytes[pos++] = 0x7d;
                return_bytes[pos++] = 0x01;
            }
            else if (source_bytes[i] == 0x7e)
            {
                return_bytes[pos++] = 0x7d;
                return_bytes[pos++] = 0x02;
            }
            else
            {
                return_bytes[pos++] = source_bytes[i];
            }
        }
 
        return ArrayUtils.subArray(return_bytes,0,pos);
 
 
    }
 
    public  byte[] unescape(byte[] cmd_bytes)
    {
        //转义还原
        int len = cmd_bytes.length;
        byte[] return_bytes = new byte[cmd_bytes.length];
 
        //int len = ByteHelper.HexString2Byte(cmd, cmd_bytes);
        int pos = 0;
        for (int i = 0; i < len; i++)
        {
            if (i == len - 1)
            {
                return_bytes[pos++] = cmd_bytes[i];
                continue;
            }
 
            if (cmd_bytes[i] == 0x7d && cmd_bytes[i + 1] == 0x02)
            {
                return_bytes[pos++] = 0x7e;
                i++;
                continue;
            }
            else if (cmd_bytes[i] == 0x7d && cmd_bytes[i + 1] == 0x01)
            {
                return_bytes[pos++] = 0x7d;
                i++;
                continue;
            }
            else
            {
                return_bytes[pos++] = cmd_bytes[i];
            }
        }
        return ArrayUtils.subArray(return_bytes,0,pos);
 
 
    }
 
}