且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换为字符串在C#中字节?

更新时间:2023-02-12 15:18:49

您必须指定 Convert.ToByte 因为你的输入字符串包含一个十六进制数字:

 字节b = Convert.ToByte(一,16); 


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

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