String Hex to byte, vb.net

2019-09-19 15:41发布

问题:

I'm struggling with an easy task. At least it looks like it should be, at first sight. I have a TextBox that contains HEX strings. They are always two hex digits in length (e.g. AA). I want to convert textbox3.Text to a Byte.

Here's what I have so far:

Dim checking As String = textbox3.Text
Dim a = Convert.ToByte(checking)
RichTextBox1.Text = a.ToString 

But it throws a SystemFormatException.

回答1:

The Convert.ToByte method provides an overload which takes a string argument followed by a number specifying the base of the value in the string. Hexadecimal is base-16. So, for instance:

Dim checking As String = textbox3.Text
Dim a As Byte = Convert.ToByte(checking, 16)
RichTextBox1.Text = a.ToString()