0

I am new to C# and I am trying to convert string into List. I was able to do so only if my dataRetured variable below doesn't have a letter. My code is below:

List<byte> response = new List<byte>();

string dataReturned = "62 07 00 00 04 05 00 01 A0";

response = dataReturned.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(s => Byte.Parse(s)).ToList();

Once I have a letter as A0 in dataReturned variable above I keep getting error in the response line since I am using Bye.Parse with A0. Is there an equivalent conversion for both integer representation and letter? Thanks

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
k_al
  • 3
  • 1
  • [How do you convert a byte array to a hexadecimal string, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa) ? – Joelius Apr 19 '21 at 21:21
  • _I was able to do so_ - No. The letters seem to indicate the the data are in hex, which means you need to convert from hex, which means your code so far is not getting the correct results for anything larger than 09. 10 in hex is 16 in decimal notation. – TaW Apr 19 '21 at 21:22

1 Answers1

3

Try this

response =
    dataReturned
        .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(s => Byte.Parse(s, NumberStyles.HexNumber))
        .ToList();

Here we added NumberStyles.HexNumber which allow you to parse hex strings.

Kit
  • 20,354
  • 4
  • 60
  • 103
Serg
  • 3,454
  • 2
  • 13
  • 17