Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string containing a hexadecimal pair to a byte?

Tags:

string

c#

hex

byte

I have a string containing a hexadecimal value. Now I need the content of this string containing the hexadecimal as a byte variable. How should I do this without changing the hexadecimal value?

like image 386
Wessel T. Avatar asked Nov 14 '25 17:11

Wessel T.


2 Answers

An alternative to the options posted so far:

byte b = Convert.ToByte(text, 16);

Note that this will return 0 if text is null; that may or may not be the result you want.

like image 184
Jon Skeet Avatar answered Nov 17 '25 07:11

Jon Skeet


If it is just a single byte in the string, you can do this:

        string s = "FF";
        byte b;


        if (byte.TryParse(s, NumberStyles.HexNumber, null, out b))
        {
            MessageBox.Show(b.ToString());  //255
        }
like image 31
John Koerner Avatar answered Nov 17 '25 09:11

John Koerner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!