我正在尝试根据byte[]
数组中的消息协议编写一个返回有效数据的程序。
我有:
STX: 0x02
ETX: 0X03
DLE: 0x10 //Delimiter
有效数据是byte[]
数组包含STX,ETX,数据和正确计算的LRC,例如:
byte[] validMsg1 = {0x02, // STX
0x10,0x2,0xA,0x10,0x10,0x7,0x8, // Data 2 A 10 7 8
0x03, // ETX
0x2^0xA^0x10^0x7^0x8^0x03}; // LRC calculated from the data (with the DLE removed) plus the ETX
无效的数据示例:
byte[] invalidMsg1 = {0x02, // STX
0x10,0x2,0xA, // Data 2 A
0x03, // ETX
0x2^0xA^0x10^0x7^0x8^0x03,
0x02, //STX
0x05,0x44};
该字节可能还包含有效数据周围的随机值:
byte[] validMsgWithRandomData1 = {0x32,0x32,0x32, //Random data
0x02, // STX
0x31,0x32,0x10,0x02,0x33, // Data 31 32 02 33
0x03, // ETX
0x31^0x32^0x02^0x33^0x03,// LRC calculated from the data (with the DLE removed) plus the ETX
0x2,0x3,0x00,0x02 //Random data
};
我的问题是当我使用带有随机数据的消息并且0x2,0x3,0x00,0x02
时它会中断,因为它看到0x02和0x03作为STX和ETX然后它计算LRC导致0x03导致这是返回:0x2,0x3,0x00
,最后的0x03为LRC。
问题是这个有效数据:
byte[] data = {
0x02, // STX
0x03, // ETX
0x00, // LRC
};
我应该返回最新的有效数据,但是这里有更好的数据:
byte[] validData = {
0x02, // STX
0x31,0x32,0x10,0x02,0x33, // Data 31 32 02 33
0x03, // ETX
0x31^0x32^0x02^0x33^0x03,// LRC calculated from the data (with the DLE removed) plus the ETX
};