2016-02-08 69 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]。