[转]System.Buffer

本文转自:http://hi.baidu.com/cyap/blog/item/51a721a1d3c8e48c461064ec.html

System.Buffer 用于操作基元类型数组,只是 MSDN 语焉不详,很容易引起误解。

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

你可能对这个结果有些意外,其实过程是下面这样的。

(1) 首先将数组按元素索引序号大小作为高低位组合成一个 "大整数"。

组合结果 : 0d0c0b0a 04030201

(2) index 表示从低位开始的字节序号。右边以 0 开始,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);

操作前 : 0d0c0b0a 04030201
操作后 : 0d0c0b0a 04ff0201

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);

bytes 组合结果 : 0d 0c 0b 0a
ints 组合结果 : 00000002 00000001

(1) 从 src 位置 1 开始提取 2 个字节,那么应该是 "0c 0b"。
(2) 写入 dst 位置 2,那么结果应该是 "00000002 0c0b0001"。
(3) ints = { 0x0c0b0001, 0x00000002 },符合程序运行结果。


MSDN:
Buffer.BlockCopy 方法

将指定数目的字节从起始于特定偏移量的源数组复制到起始于特定偏移量的目标数组。

public static void BlockCopy (
Array src,
int srcOffset,
Array dst,
int dstOffset,
int count
)

参数

src

源缓冲区。

srcOffset

src 的字节偏移量。

dst

目标缓冲区。

dstOffset

dst 的字节偏移量。

count

要复制的字节数。

 

posted on 2011-05-05 12:57  freeliver54  阅读(1833)  评论(0编辑  收藏  举报

导航