简体   繁体   中英

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

您必须指定要在Convert.ToByte使用的基数,因为您的输入字符串包含一个十六进制数:

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

您可以使用Convert助手类的ToByte函数:

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

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

You can use UTF8Encoding :

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

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