如何转换为字符串在C#中字节? [英] How do I convert a string to byte in C#?

查看:506
本文介绍了如何转换为字符串在C#中字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能转换这个字符串为字节

 字符串=0x2B访问?; 



我试过这个代码(字节)(a)条;但它说:




无法将类型字符串字节...




当我尝试这种代码, Convert.ToByte(一); byte.Parse(一); ,它说:




输入字符串的不正确的格式...




,这是什么?



正确的代码,但是,当我宣布它例如在阵列,这是可以接受的...



例如:

 字节[] D =新的字节[1] = {} 0x2a; 


解决方案

您必须指定<$使用该基地C $ C> 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);

这篇关于如何转换为字符串在C#中字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆