Kevin Boyd
Kevin Boyd

Reputation: 12379

C#, How to split a byte array by delimiter?

I have a byte array that contains a collection of 2 byte hexadecimal numbers separated by ','. How could it be split by ',' and then the numbers be converted to integers?

The byte array contains values in ascii format.

edit: Example

My valid character range is 0 to 9 ,A to F and comma so my stream should look like

70, 67, 65, 57, 44, 55, 68, 66, 53, 44....

this would be equivalent to hexadecimal

FCA9 and 7DB5

Upvotes: 4

Views: 7560

Answers (3)

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

This should work, though my C# is a bit rusty...

byte[]    input = { 1, 0, 0, 0, ',', 10, 15, ',', 100, 0, 0, 0, ',' };
List<int> output = new List<int>();

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] };
             output.Add(BitConverter.ToInt32(tmp, 0));
         }

         lastIndex = i + 1;
    }
}

Upvotes: 1

rfcdejong
rfcdejong

Reputation: 2320

I would convert the byte array to string and then use String.Split(',')

Upvotes: 2

Joshua Honig
Joshua Honig

Reputation: 13225

If your byte array is truly ASCII encoded (ONE byte per character), then the following would work:

int[] ints = Encoding.ASCII.GetString(asciiEncodedBytes).Split(',')
             .Select(x => Convert.ToInt32(x,16)).ToArray();

This will handle mixed case and variable length hex numbers, too.

Upvotes: 6

Related Questions