简体   繁体   中英

C# Windows Form Textbox input to byte array

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!

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();

you can use this code for cast string to byte array

 var input = textbox.Text;  
 byte[] bytes = Encoding.ASCII.GetBytes(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM