代码改变世界

c# Buffer学习笔记

2010-08-31 14:09  田志良  阅读(12409)  评论(1编辑  收藏  举报

System.Buffer 以字节数组(byte[])方式操作基元类型数组,相当于 C 语言的 (char*)int_pointer 指针操作。

1. Buffer.ByteLength

该方法范围基元类型数组累计有多少字节组成。

var bytes = new byte[] { 1, 2, 3 };
var shorts = new short[] { 1, 2, 3 };
var ints = new int[] { 1, 2, 3 };

Console.WriteLine(Buffer.ByteLength(bytes));  // 1 byte * 3 elements = 3
Console.WriteLine(Buffer.ByteLength(shorts)); // 2 byte * 3 elements = 6
Console.WriteLine(Buffer.ByteLength(ints)); // 4 byte * 3 elements  = 12
也就是说该方法结果等于"基元类型字节长度 * 数组长度" 。

 

2. Buffer.GetByte

public static byte GetByte(Array array, int index)
这个方法原型很容易引起误解。

var ints = new int[] { 0x04030201, 0x0d0c0b0a };
var b = Buffer.GetByte(ints, 2); // 0x03
从左到右顺序存储 int,按照小端模式内存数据就是:

01 02 03 04 0a 0b 0c 0d
index 2 的结果自然是 0x03。

 

3. Buffer.SetByte

public static void SetByte(Array array, int index, byte value)
有了上面的解释,这个就比较好理解了。

var ints = new int[] { 0x04030201, 0x0d0c0b0a };
Buffer.SetByte(ints, 2, 0xff);
操作前 :

01 02 03 04 0a 0b 0c 0d
操作后 :

01 02 ff 04 0a 0b 0c 0d
4. Buffer.BlockCopy

public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
看个例子就明白了。

var bytes = new byte[] { 0x0a, 0x0b, 0x0c, 0x0d};
var ints = new int[] { 0x00000001, 0x00000002 };

Buffer.BlockCopy(bytes, 1, ints, 2, 2);
拷贝前 ints 的内存布局:

01 00 00 00 02 00 00 00
从 bytes Index 1 拷贝 2 个字节到 ints Index 2 后内存布局:

01 00 0b 0c 02 00 00 00