This question is related to: C# How to extract bytes from byte array? With known starting byte
I have "100 bytes byte[]", that is composed with several "14 bytes byte[]" that occur in the bigger byte randomly.
My smaller byte[] start with the (byte) 0x55 and end 16 bytes later
I'm using the code:
byte[] results = new byte[16];
int index = Array.IndexOf(readBuffer, (byte)0x55, 2);
Array.Copy(readBuffer, index, results, 0, 16);
But with this, I only get the first occurrence of my smaller byte[].
How do I get ALL the smaller byte[] blocks?
PS: I'm working with .Net Micro Framework
I am presuming that your message is composed of a starting cookie byte
0x55, 14 bytes of actual data, and 1 checksum byte (since you used 14 and 16 bytes interchangeably). The only way for randomly occuring subarrays to make sense is to have a checksum value at the end, to confirm your starting byte is actually a valid cookie (instead of being a data byte).(edited after your update)
So, your actual data is
0x55 + 1syncbyte + 2 checksum + 12 databytes, meaning that your function should:Start with index
i= 0 and repeat whilei + 15< input length:i.iand start again.i + 1.iand start again.i + 2/i + 3, calculate actual data checksum and compare.iand start again.i + 4toi + 15into a segment of size 12.You can do skip to the first occurrence of
0x55usingArray.IndexOf, but since you need to keep track of the index anyway, you may as well just do the check yourself and simplify the code (algorithmic complexity is the sameO(n)).One way to code this would be something like:
And you would use it in a
foreachloop to iterate over segments:Or you can get a list of segments if you want to iterate through elements several times:
Since you are new to C# (and generally programming), I suggest you place a breakpoint inside the method and go step by step to understand what's going on.