12,289,383 members (70,338 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 18: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>```
Refer the below link.

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();
}
}
}```

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 388 KARTHIK Bangalore 305 Dave Kreskowiak 175 F-ES Sitecore 140 ppolymorphe 139
 OriginalGriff 7,960 ppolymorphe 4,897 CHill60 4,870 Sergey Alexandrovich Kryukov 4,239 KARTHIK Bangalore 4,067

Advertise | Privacy | Mobile
Web01 | 2.8.160518.1 | Last Updated 18 Dec 2012