Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

byte

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};
like image 698
monkeydluffy Avatar asked May 11 '12 18:05

monkeydluffy


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

Is hex same as byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.


5 Answers

You can use UTF8Encoding:

public static byte[] StrToByteArray(string str)
{
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}
like image 135
Frederic Avatar answered Oct 12 '22 12:10

Frederic


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);
like image 26
BrokenGlass Avatar answered Oct 12 '22 11:10

BrokenGlass


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

byte b = Convert.ToByte(a, 16);
like image 42
aleroot Avatar answered Oct 12 '22 11:10

aleroot


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);
like image 42
BluesRockAddict Avatar answered Oct 12 '22 13:10

BluesRockAddict


byte b = Convert.ToByte(a, 16);
like image 38
Douglas Avatar answered Oct 12 '22 12:10

Douglas