【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