如何在 C# 中将字符串转换为字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10556805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a string to byte in C#?
提问by monkeydluffy
How can I convert this string into a byte?
如何将此字符串转换为字节?
string a = "0x2B";
I tried this code, (byte)(a); but it said:
我试过这段代码,(byte)(a); 但它说:
Cannot convert type string to byte...
无法将类型字符串转换为字节...
And when I tried this code, Convert.ToByte(a);and this byte.Parse(a);, it said:
当我尝试这段代码Convert.ToByte(a);和 this 时byte.Parse(a);,它说:
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};
采纳答案by BrokenGlass
You have to specify the base to use in Convert.ToBytesince your input string contains a hex number:
您必须指定要使用的基数,Convert.ToByte因为您的输入字符串包含一个十六进制数:
byte b = Convert.ToByte(a, 16);
回答by BluesRockAddict
Update:
更新:
As others have mentioned, my original suggestion to use byte.Parse()with NumberStyles.HexNumberactually won't work with hex strings with "0x" prefix. The best solution is to use Convert.ToByte(a, 16)as suggested in other answers.
正如其他人所提到的,我最初使用byte.Parse()with 的建议NumberStyles.HexNumber实际上不适用于带有“0x”前缀的十六进制字符串。最好的解决方案是Convert.ToByte(a, 16)按照其他答案中的建议使用。
Original answer:
原答案:
Try using the following:
byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
尝试使用以下方法:
byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
回答by aleroot
回答by Douglas
byte b = Convert.ToByte(a, 16);
回答by Frederic
You can use UTF8Encoding:
您可以使用UTF8Encoding:
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}

