0

Here is the code i've come up with so far for this but it throws this exception when I input a letter value such as AA.

"An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format."

Also I would like to include some error message if the user inputs an invalid value. Any help would be great, thanks.

               private void GPIO_Click(object sender, EventArgs e)
                {
                    string hex = WriteValue.Text;
                    string[] hex1 = hex.Split(',');
                    byte[] bytes = new byte[hex1.Length];

                    for (int i = 0; i < hex1.Length; i++)
                    {
                        bytes[i] = Convert.ToByte(hex1[i]);
                    }

                    for (int i = 0; i < hex1.Length; i++)
                    {
                    GPIO(h[index], dir, bytes[i]);
                    ReadValue.Text += bytes[i].ToString();
                    }
                 }
john
  • 159
  • 3
  • 16

2 Answers2

2

You need to call it with base set to 16 (hexadecimal).

Convert.ToByte(text, 16)

Many duplicates:

c# string to hex , hex to byte conversion

How do you convert Byte Array to Hexadecimal String, and vice versa?

Community
  • 1
  • 1
vojta
  • 5,591
  • 2
  • 24
  • 64
1

When you arrive at

bytes[i] = Convert.ToByte(hex1[i]);

the value of hex1[i] is "AA"

Your app fails here because you cannot fit "AA" as a string in a single byte.

If you're looking for a byte array conversion of the string, you will want to split that value into chars ; like this :

  string hex = "AA";
  string[] hex1 = hex.Split(',');
  List<byte[]> byteArrays = List<byte[]>();

  foreach (string t in hex1)
  {
        int byteIndex = 0;
        byte[] newArray = new byte[hex1.Length];
        foreach(char c in t)
        {
              newArray [byteIndex] = Convert.ToByte(c);
              byteIndex++;
        }
        byteArrays.add(newArray);
  }

But i don't think that's what you're after. you're looking to parse decimal values represented as a string.

Timothy Groote
  • 8,614
  • 26
  • 52