c# byte數組各種操作


1、網絡字節序轉換

            float m = 5f;
            var btValue = BitConverter.GetBytes(m).Reverse().ToArray();

  2、byte數組合並

            byte[] data = new byte[10];
            byte[] counts =new byte[3];
            byte[] ndata = new byte[data.Length + counts.Length];
            data.CopyTo(ndata, 0);
            counts.CopyTo(ndata, data.Length);

  3、string和byte[]轉換

            string轉byte[]:
            byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
            
            byte[]轉string:
            string str = System.Text.Encoding.Default.GetString ( byteArray );
            
            string轉ASCII byte[]:
            byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );
            
            ASCII byte[]轉string:
            string str = System.Text.Encoding.ASCII.GetString ( byteArray );

  4、字符串分割成數組

string[] b = a.Split('|');

  5、int轉換成16進制字節

            int a = 58;
            byte b = Convert.ToByte(a);

  6、byte[]截取

 byte[] test = buffer.Skip(24).Take(16).ToArray();//從第24位開始截取長度16

  7、定義一個list 添加后 轉換成byte[]

List<byte> frameBytes = new List<byte>();
frameBytes.Add(0x9E);	
byte[] phoneNumByte=new byte[]{0x01,0x03,0x05,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00};//定義一個數組			
for (int i = 0; i < phoneNumByte.Length; i++)
 {
   frameBytes.Add(phoneNumByte[i]);
 }
frameBytes = frameBytes.Concat(dataBody).ToList<byte>();//兩個list合並
byte[] transByte = frameBytes.ToArray();//list轉byte[]
// List<byte> b=transByte.ToList();//byte[]轉list

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM