Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 966
Kevin Boyd Avatar asked Jan 17 '23 09:01

Kevin Boyd


2 Answers

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.

like image 52
Joshua Honig Avatar answered Jan 27 '23 14:01

Joshua Honig


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

like image 34
rfcdejong Avatar answered Jan 27 '23 13:01

rfcdejong