Reputation: 1453
I have a textbox in my C# GUI in which I want the user to let it enter hexadecimal values. Example:
input = 0x01 0xD 0x0A
After that, I want the hexadecimal value to be converted to bytes. What would my approach to this?
I do know in the end I need to use:
bytes = new byte[amount of hex values]
{
//here are my hexadecimal values
};
But what dynamic approach could I use to convert the string to separate hexa-values at runtime?
I have found:
string str = "7E 00 00 FF 00 00 00 00 00 00 00 00 00 00 00 00 00 FF";
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
serialport.Write(bytes, 0, bytes.Length);
but this wouldn't work at runtime (the amount of hexa values is set at compile time?)
Upvotes: 0
Views: 956
Reputation: 859
LINQ:
var bytes = yourInput.Text.Split( ' ' ).Select( h => byte.Parse( h, NumberStyles.AllowHexSpecifier ) ).ToArray();
Upvotes: 1