How do I convert a Hexidecimal string to byte in C#?

24,939

Solution 1

You have to specify the base to use in Convert.ToByte since your input string contains a hex number:

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

Solution 2

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

Solution 3

You can use the ToByte function of the Convert helper class:

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

Solution 4

You can use UTF8Encoding:

public static byte[] StrToByteArray(string str)
{
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}

Solution 5

Update:

As others have mentioned, my original suggestion to use byte.Parse() with NumberStyles.HexNumber actually won't work with hex strings with "0x" prefix. The best solution is to use Convert.ToByte(a, 16) as suggested in other answers.

Original answer:

Try using the following:

byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
Share:
24,939
monkeydluffy
Author by

monkeydluffy

Updated on July 05, 2022

Comments

  • monkeydluffy
    monkeydluffy almost 2 years

    How can I convert this string into a byte?

    string a = "0x2B";
    

    I tried this code, (byte)(a); but it said:

    Cannot convert type string to byte...

    And when I tried this code, Convert.ToByte(a); and this byte.Parse(a);, it said:

    Input string was not in a correct format...

    What is the proper code for this?

    But when I am declaring it for example in an array, it is acceptable...

    For example:

    byte[] d = new byte[1] = {0x2a};