0

I am new to C# programming (or programming in general) and having a problem of setting raw textbox string value into byte value within a byte array.

My question is how can I convert the string HEX value from a text box string input into an exact byte value within a byte array as shown in the example code below.

I get the following error from my example code below;

"System.FormatException: 'The input string '0x50' was not in a correct format.'"

I have read up on byte, char, and string data types but still cannot really understand how to slot in the HEX string value into the byte value.

Thanks for any help.

string byte3 = "0x50";//value from textBox at runtime
string byte4 = "0xEF";//value from textBox at runtime

byte[] bytes = new byte[5];
bytes[0] = 0xAB; //hard coded value
bytes[1] = 0x0F; //hard coded value
bytes[2] = 0x02; //hard coded value
bytes[3] = Convert.ToByte(byte3); // from textbox string to byte value
bytes[4] = Convert.ToByte(byte4); // from textbox string to byte value

void ThenIUseTheBytesArrayInAnotherMethod(bytes){

}

I have read up on byte, char, and string data types but still cannot really understand how to slot in the HEX string value into the byte value.

Buvag
  • 9
  • 1
  • 3
    You can specify a base to `Convert.ToByte(byte3, 16)`. – 001 Mar 21 '23 at 13:52
  • I didn't think it would like the "0x" part but it works. – Deolus Mar 21 '23 at 13:59
  • Now `Convert.ToByte(` can't understand the `0x` prefix for hexadecimal numbers. Therefore, you must truncate the string and explicitly specify the base of the number. [`Convert.ToByte()`][1] has an overload of the method with 2 parameters: ``` public static byte ToByte (string? value, int fromBase); ``` – Vadim Martynov Mar 21 '23 at 14:08
  • It converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer. `value` parameter is a string that contains the number to convert. `fromBase` is a base of the number in value, which must be 2, 8, 10, or 16. ``` bytes[3] = Convert.ToByte(byte3.Substring(2), 16); bytes[4] = Convert.ToByte(byte4.Substring(2), 16); ``` [1]: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tobyte – Vadim Martynov Mar 21 '23 at 14:08
  • Thank you very much for all the response. It has solved my issue and gained more understanding, direct to the point. I hope the admin can leave this question on, because the solution is direct and clear than the suggested "None" duplicate questions especially for new commers like me. Thanks again. – Buvag Mar 21 '23 at 14:19

0 Answers0