【C#】byte[]数据转化相关操作

一、int、float、double转byte[]
均使用System.BitConverter.GetBytes()。

1 int iii = 1;
2 float fff = 1234.12346f;
3 double ddd = 12.1264567;
4 
5 byte[] b1,b2 = new byte[4];
6 byte[] b3 = new byte[8];
7 b1 = BitConverter.GetBytes(iii);
8 b2 = BitConverter.GetBytes(fff);
9 b3 = BitConverter.GetBytes(ddd);

二、string转byte[]

1 string str1 = "11111111";
2 byte[] b4 = Encoding.Default.GetBytes(str1);

三、byte[]转int、float、double、string
还是用BitConverter

1 byte[] b5 = new byte[4] { 0x01, 0x02, 0x03, 0x04 };
2 byte[] b6 = new byte[8] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; 
3 int i2 = BitConverter.ToInt32(b5, 0);
4 float f2 = BitConverter.ToSingle(b5, 0);
5 double d2 = BitConverter.ToDouble(b6, 0);
6 string str2 = BitConverter.ToString(b6, 0);

四、两个byte[]之间截取、复制
用System.Array可以完成对数组的创建、搜索、复制等操作

1 byte[] b7 = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 };
2 byte[] b8 = new byte[2];
3 Array.Copy(b7, 2, b8, 0,2);

 

转载于:https://www.cnblogs.com/jasminek/p/9360897.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值