2016-02-08 71 views
2

這可能是一個真正的開瓶器的問題,但我一直在閱讀關於這一點,我覺得很難理解。c#緩衝區說明

這是關於此主題的msdn頁面的示例(只是略小一些)。

using System; 

class SetByteDemo 
{ 
    // Display the array contents in hexadecimal. 
    public static void DisplayArray(Array arr, string name) 
    { 
     // Get the array element width; format the formatting string. 
     int elemWidth = Buffer.ByteLength(arr)/arr.Length; 
     string format = String.Format(" {{0:X{0}}}", 2 * elemWidth); 

     // Display the array elements from right to left. 
     Console.Write("{0,7}:", name); 
     for (int loopX = arr.Length - 1; loopX >= 0; loopX--) 
      Console.Write(format, arr.GetValue(loopX)); 
     Console.WriteLine(); 
    } 

    public static void Main() 
    { 
     // These are the arrays to be modified with SetByte. 
     short[] shorts = new short[2]; 

     Console.WriteLine("Initial values of arrays:\n"); 

     // Display the initial values of the arrays. 
     DisplayArray(shorts, "shorts"); 

     // Copy two regions of source array to destination array, 
     // and two overlapped copies from source to source. 
     Console.WriteLine("\n" + 
      " Array values after setting byte 1 = 1 and byte 3 = 200\n"); 
     Buffer.SetByte(shorts, 1, 1); 
     Buffer.SetByte(shorts, 3, 10); 

     // Display the arrays again. 
     DisplayArray(shorts, "shorts"); 
     Console.ReadKey(); 
    } 
} 

SetByte應該很容易理解,但如果我做SetByte操作數組看起來像這樣

{short[2]} 
    [0]: 0 
    [1]: 0 

做第一Buffer.SetByte(shorts, 1, 1);後陣之前打印短褲陣列變得

{short[2]} 
    [0]: 256 
    [1]: 0 

並且在設置Buffer.SetByte(shorts, 3, 10);之後,陣列變爲

{short[2]} 
    [0]: 256 
    [1]: 2560 

最後,在本例中,他們打印陣列由右至左:

0A00 0100 

我不明白這是如何工作,有人可以給我一些有關此信息?

回答

2

.NET類型使用little endianness。這意味着short,int等的第一個字節(實際上是0)包含最低有效位。

設置陣列之後,它看起來這是byte[]

0, 1, 0, 10 

由於short[]它這樣解釋:

0 + 1*256 = 256, 0 + 10*256 = 2560 
2

緩衝區類允許您操作內存,如果你是使用c中的一個void指針,就像memcpy,memset等等的總和,以便以.net的快速方式處理內存。

當你通過了「短褲」陣列,Buffer類「看到」它作爲一個指針連續四個字節(雙短褲,他們每個人的兩個字節):

|[0][1]|[2][3]| 
    short short 

所以未初始化數組外觀像這樣:

|[0][0]|[0][0]| 
    short short 

當你做你Buffer.SetByte(shorts, 1, 1);指示Buffer類更改字節數組的第二個字節,所以這將是:

|[0][1]|[0][0]| 
short short 

如果您將兩個字節(0x00,0x01)轉換爲一個短整型爲0x0100(請注意,因爲這些是兩個字節一個接一個,但順序相反,這是因爲C#編譯器使用的是小端)或256

第二行基本上沒有相同Buffer.SetByte(shorts, 3, 10);改變第三個字節10:

|[0][1]|[0][10]| 
short short 

然後0x00,0x0A作爲短是0x0A00或2560。

0

我認爲人們可能會苦惱的部分是Buffer.SetByte()方法基本上迭代數組的方式不同於數組indexer []的常規賦值,該方法將根據包含類型的寬度來分隔數組短褲/雙打/等)而不是字節...使用您的例子: 短陣列通常被看作 arr = [xxxx, yyyy](以16爲基數) 但SetByte方法「看到」它爲: arr = [xx, yy, zz, ww]

所以像Buffer.SetByte(arr, 1, 5)這樣的調用將解決arry中的第二個字節,該字節仍然在第一個短的內部。在那裏設定值,就是這樣。 結果應該如下:

[05 00,00 00] in hex or [1280,0]。