(C#基礎) byte[] 之初始化, 賦值,轉換。


byte[] 之初始化賦值

用for loop 賦值當然是最基本的方法,不過在C#里面還有其他的便捷方法。

1. 創建一個長度為10的byte數組,並且其中每個byte的值為0.

byte[] myByteArray = new byte[10];

C# 在創建數值型(int, byte)數組時,會自動的把數組中的每個元素賦值為0.  (注:如果是string[], 則每個元素為的值為null. 

 

2. 創建一個長度為10的byte數組,並且其中每個byte的值為0x08. 

byte[] myByteArray = Enumerable.Repeat((byte)0x08, 10).ToArray();

用linq來賦值,語句只要一條, 當然我們還可以賦值不同的,但是有一定規律的值。

byte[] res= Enumerable.Range(1, 1000).Select(c=>Convert.ToByte(c)).ToArray();

 

3. 直接賦值

byte[] myByteArray = new byte[] { 0x01, 0x02, 0x03 };

 

byte[] ---> ushort

            byte[] array = new byte[] { 0xFE, 0x00 };

            ushort register = BitConverter.ToUInt16(array, 0);

上述轉換后register 的值為 0x00FE

            byte[] array = new byte[] { 0x02, 0x01 ,0x04, 0x03 };

            ushort register = BitConverter.ToUInt16(array, 0);

上述轉化后,其實只是取了array[0], array[1].的值,最后register 的值是 0x00010002, 即258

byte[] -> string

public static string ByteArrayToString(byte[] ba)
{
  string hex = BitConverter.ToString(ba);
  return hex.Replace("-","");
}

 

ushort ---> byte[]

            ushort register = 0x00F0;

            byte[] arr = BitConverter.GetBytes(register); 

在PC系統里, arr[0] = 0xF0(地位), arr[1] = 0x00 . 

互換ushort中的兩個字節

            ushort number = 0x00F0;

            byte[] temp = BitConverter.GetBytes(number);
            Array.Reverse(temp); 

            ushort a = BitConverter.ToUInt16(temp, 0);

            ushort b = (ushort)(number << 8 | ((number & 0xFF00) >> 8));

 

引自: http://www.cnblogs.com/fdyang/archive/2013/10/20/3378974.html


免責聲明!

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



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