4

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?

2
  • stackoverflow.com/questions/311165/… Commented Feb 13, 2011 at 18:02
  • Not a duplicate (wrt C#) as far as I can tell. There are many variations, but this is specific ("xx" -> byte) and warrants a simpler answer than a number of the more complex scenarios. Commented Feb 13, 2011 at 19:14

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn, i even looked at the Convert.ToByte method but totally didn't spot that overload which takes the base as parameter...
2

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
        }

Comments

2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.