I have a buffer of length 256 that receives byte sequences from bluetooth. The actual packet that I need to extract is starting and ending with byte 126
. I want to extract the latest packet in the buffer using LINQ.
What I am doing now is checking for last index of 126
and then count backward until I reach another 126
. There are some pitfalls as well, for example, two adjacent packet can result in two bytes of 126
next to eachother.
Here is a sample of buffer:
126 6 0 5 232 125 93 126 126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126 126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126 126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126 126 69 0 0
So the information I have is:
- Packet starts and ends with byte value of 126
- the next byte after the starting index does have value of 69
- the 3 last byte right befor the ending byte of 126 is a CRC of the whole packet that I know how to calculate, so after extracting a packet I can check this CRC to see if I have the right packet
So at the end I want to have an array or list that contains the correct packet. for example:
126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126
Can you give me a fast soloution of extracting this packet from buffer?
This is what I'v tried so far....it fails as it cant really return the correct packet I am looking for:
var data = ((byte[])msg.Obj).ToList(); //data is the buffer
byte del = 126; //delimeter or start/end byte
var lastIndex = data.LastIndexOf(del);
var startIndex = 0;
List<byte> tos = new List<byte>(); //a new list to store the result (packet)
//try to figure out start index
if(data[lastIndex - 1] != del)
{
for(int i = lastIndex; i > 0; i--)
{
if(data[i] == del)
{
startIndex = i;
}
}
//add the result in another list
for(int i = 0; i <= lastIndex - startIndex; i++)
{
tos.Add(data[i]);
}
string shit = string.Empty;
foreach (var b in tos)
shit += (int)b + ", ";
//print result in a textbox
AddTextToLogTextView(shit + "\r\n");
}