monkeydluffy
monkeydluffy

Reputation: 229

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

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};

Upvotes: 12

Views: 25194

Answers (5)

Frederic
Frederic

Reputation: 760

You can use UTF8Encoding:

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

Upvotes: 2

aleroot
aleroot

Reputation: 72636

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

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

Upvotes: 4

BluesRockAddict
BluesRockAddict

Reputation: 15683

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);

Upvotes: 2

Douglas
Douglas

Reputation: 54887

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

Upvotes: 5

BrokenGlass
BrokenGlass

Reputation: 160902

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);

Upvotes: 13

Related Questions