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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM