c#中各种数据类型的转化

                                        c#中各种数据类型的转化
对于初学者来说,在编写c#程序时最头痛的就是要进行各种数据类型的转换,

由于对.net开发环境的不熟悉以及系统提供的API的不了解,在处理程序时占用

了很长的时间,笔者虽然做c#的开发时间不长,但对数据之间的转化也有了一

定的心得,现在共享出来希望对大家能有所帮助。

1.int型转化为string
int i;//i可根据自己的需要进行初始化
string a = i.ToString();

2.string转化为byte[]

方法1:
string t;//要转化的字符串
char[] m = t.ToCharArray();
byte[] n = new byte[m.Length];//转化的结果数组
for ( i = 0; i < m.Length; i++)
{
   n[i] = (byte)m[i];
}

方法2:
利用系统提供的函数
string str;
Byte[] bt = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray);

3.int型转化为byte[]

方法1:
int i;
byte[] temp = new byte[4];
int pos;
for (pos = 0; pos < 4; pos++)
{
temp[pos] = (byte)(i & 0xff);
i >>= 8;
if (i == 0) break;
}

方法2:
利用系统提供的函数
int i;
byte[] tdata = new byte[4];
data = System.BitConverter.GetBytes(i);

4.byte[]转化为string

方法1:
byte[] tmp;
string str =new System.Text.ASCIIEncoding ().GetString (tmp );

方法2:
byte[] tmp;
string str = System.Text.Encoding.ASCII.GetString(tmp);

5.string类型转化为int

方法1:
string  str;
int i = Convert.ToInt32(str);

方法2:
string  str;
int i = Int32.Parse(str);

6.byte[]转换为int

方法1:

int res = 0; //结果
int temp = 0;
byte[] result;//可由上文得到,或自己进行初始化
for (int h = 3; h>=0; h--)
{
res<<= 8;
temp = result[h] & 0xff;
res |= temp;
}

方法2:
byte[] result;
int res = System.BitConverter.ToInt32(result,result想转化的起始位置);

大家有更好的方法的话,可以进行交流!
e-mail:guduchuangtianxia@sina.com.cn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值