Reputation: 159
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();
}
}
Upvotes: 0
Views: 1965
Reputation: 8643
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.
Upvotes: 1
Reputation: 5651
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?
Upvotes: 2