Home > OS >  Split a slice of bytes after a given separator/delimiter
Split a slice of bytes after a given separator/delimiter

Time:10-14

How can you split a slice of bytes after a given separator/delimiter in C#?

Let say you have this byte array: byte[] array = {1, 0x2C, 2, 0x2C, 3, 4, 5};

and your delimiter is 0x2C

The wanted result should be: array = {1, 2, 3}

Can someone please show how that is done correct?

i want to: split a byte array into sub-bytes based on specified delimiting byte

CodePudding user response:

As far as I can see (reverse engineering) you want:

  • having an array, say {1, 0x2C, 2, 0x2C, 3, 4, 5} and delimiter 0x2C
  • you want to split the array by delimiter and return first items of each group when available:
{1, 0x2C, 2, 0x2C, 3, 4, 5}
      ^        ^
      Split by these

Groups are
  {1}
  {2}
  {3, 4, 5}

First items of each group are
  {1, 2, 3}  

If its your case (fiddle yourself)

using System.Linq;

...

byte[] array = {1, 0x2C, 2, 0x2C, 3, 4, 5};

byte delimiter = 0x2C;

List<byte> list = new();

if (array.Length > 0 && array[0] != delimiter)
  list.Add(array[0]);

for (int i = 0; i < array.Length - 1;   i) 
  if (array[i] == delimiter && array[i   1] != delimiter)
    list.Add(array[i   1]);

byte[] result = list.ToArray();
  • Related