I'm very new to C# and have been struggling with an application for days- hopefully someone can help! Sorry if this is a duplicate of a previous question...
I have a Windows Forms programme which allows a user to place hex values in to a textbox which must then be placed in to a byte array and sent via serial to a hardware device.
I have validated my theory by manually initiating a byte array with the correct hex values and confirm that I can get the required response from the hardware. But I can't find a way to add the string values in the textbox directly to the byte array without changing format.
For example I have string: string data = "0x1b, 0x02, 0x43, 0x20, 0xff, 0x1b, 0x03"; And I want to place this data to a byte array: byte[] bytesToSend = { 0x1b, 0x02, 0x43, 0x20, 0xff, 0x1b, 0x03 };
How do I go about this?
Thanks in advance!
CodePudding user response:
Maybe this can help:
string data = "0x1b, 0x02, 0x43, 0x20, 0xff, 0x1b, 0x03";
byte[] bytes = data.Split(',').Select(x => Convert.ToByte(x.Trim(), 16)).ToArray();
CodePudding user response:
you can use this code for cast string to byte array
var input = textbox.Text;
byte[] bytes = Encoding.ASCII.GetBytes(input);