C#(99):System.Buffer 以字节数组(Byte[])操作基元类型数据

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

结果 : new int[] { 0x04ff0201, 0x0d0c0b0a };

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

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

  • src:源缓冲区。
  • srcOffset:src 的字节偏移量。
  • dst:目标缓冲区。
  • dstOffset:dst 的字节偏移量。
  • count:要复制的字节数。

例一:arr的数组中字节0-16的值复制到字节12-28:(int占4个字节byte )

int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
Buffer.BlockCopy(arr, 0 * 4, arr, 3 * 4, 4 * 4);
foreach (var e in arr)
{
     Console.WriteLine(e);//2,4,6,2,4,6,8,16,18,20
}
例二:
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 },符合程序运行结果。

原文地址:https://www.cnblogs.com/springsnow/p/9428671.html