You can iterate over the array with a for loop.
int? lastIndex = null;
byte[] subArray;
for(int index = 0; index < bytes.Length; index++)
{
if(bytes[index] != 0xAA) continue;
if(lastIndex is not null)
{
int length = index - (int)lastIndex;
subArray = new byte[length];
Array.Copy(bytes, (int)lastIndex, subArray, 0, length);
//Do something with subArray
}
lastIndex = index;
}
if(lastIndex is null)
{
// Handle the case when no 0xAA is found
System.Console.WriteLine("No instances of 0xAA found");
return;
}
subArray = new byte[bytes.Length - (int)lastIndex];
Array.Copy(bytes, (int)lastIndex, subArray, 0, bytes.Length - (int)lastIndex);
//Do something with last subArray
This finds occurences of 0xAA and creates the subarrays as copies. If you don't need a copy you may also create spans of the array regions like so:
int? lastIndex = null;
Span<byte> span;
for(int index = 0; index < bytes.Length; index++)
{
if(bytes[index] != 0xAA) continue;
if(lastIndex is not null)
{
span = bytes.AsSpan((int)lastIndex, index - (int)lastIndex);
//Do something with span
}
lastIndex = index;
}
if(lastIndex is null)
{
System.Console.WriteLine("No instances of 0xAA found");
return;
}
span = bytes.AsSpan((int)lastIndex, bytes.Length - (int)lastIndex);
//Do something with last span
If you assign something to an element of span it will change your original array. If you don't want this you can use ReadOnlySpan<byte> in exactly the same way. But even then if you change the original array's values the span will reflect those changes.