简体   繁体   中英

How do I convert a string containing a hexadecimal pair to a 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?

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.

String strHex = "ABCDEF";
Int32 nHex = Int32.Parse(strHex, NumberStyles.HexNumber);
Byte[] bHex = BitConverter.GetBytes(nHex);

I think that's what you're looking for. If not, post an update with a more explicit definition of what you're looking for.

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
        }

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