12,823,984 members (46,490 online)
Rate this:
See more:
I have to split bytes based on 0x1E
`byte[] input = { 0x1E, 0x30, 0x30, 0x31, 0x1E };`

how to split byte array?
Posted 27-Nov-12 19:50pm
Mohd. Mukhtar 28-Nov-12 1:03am

What have you tried?

Rate this:

## Solution 1

Hi,

Try with below line of code.

```byte[]    input = { 0x1E, 0x30, 0x30, 0x31, 0x1E };
List<string> output = new List<string>();

int lastIndex = 0;

for (int i = 0; i < input.Length; i++)
{
if (input[i] == ',')
{
if (i - lastIndex == 4)
{
byte[] tmp = { input[i - 4], input[i - 3], input[i - 2], input[i - 1] };
}
lastIndex = i + 1;
}
}
</string>```

http://stackoverflow.com/questions/11816295/splitting-a-byte-into-multiple-byte-arrays-in-c-sharp[^]
Rate this:

## Solution 2

Hi,

try this,

```
static void Main()
{
byte[] arr = { 0x1E, 0x23, 0x1E, 0x33, 0x44, 0x1E };
byte split = 0x1E;
List<byte[]> result = new List<byte[]>();
int start = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == split && i!=0)
{
byte[] _in = new byte[i - start];
Array.Copy(arr, start, _in, 0, i - start);
start = i+1;
}
else if (arr[i] == split && i == 0)
{
start = i + 1;
}
else if (arr.Length - 1 == i && i != start)
{
byte[] _in = new byte[i - start+1];
Array.Copy(arr, start, _in, 0, i - start+1);
}

}
}
```

--SRJ

Rate this:

## Solution 3

Thank u all for reply i have acheived this thru yield keyword below is a sample
```class Program
{
static IEnumerable<byte[]> Packetize(IEnumerable<byte> stream)
{
var buffer = new List<byte>();
foreach (byte b in stream)
{
if (b == 0x1E||b==0x1F||b==0x07)
{
buffer.Remove(b);
yield return buffer.ToArray();
buffer.Clear();
}
}
if (buffer.Count > 0)
yield return buffer.ToArray();
}

static void Main(string[] args)
{
byte[] input = {0x1E, 0x30, 0x30, 0x31, 0x1E, 0x40, 0x41, 0x42, 0x1E, 0x1F };
foreach (var packet in Packetize(input))
{
foreach (var b in packet) Console.Write("{0:x2} ", b);
Console.WriteLine();
}
}
}```

Top Experts
Last 24hrsThis month
 CPallini 120 AnvilRanger 110 Karthik Bangalore 110 Bryian Tan 105 OriginalGriff 95
 OriginalGriff 5,182 Graeme_Grant 3,832 Karthik Bangalore 3,611 ppolymorphe 2,639 Jochen Arndt 2,611