日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C#使用System.Buffer以字節(jié)數(shù)組Byte[]操作基元類型數(shù)據(jù)_C#教程

作者:springsnow ? 更新時間: 2022-07-04 編程語言

1. Buffer.ByteLength:計算基元類型數(shù)組累計有多少字節(jié)組成。

該方法結果等于"基元類型字節(jié)長度 * 數(shù)組長度"

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:獲取數(shù)組內(nèi)存中字節(jié)指定索引處的值。

public static byte GetByte(Array array, int index)

var ints = new int[] { 0x04030201, 0x0d0c0b0a };
var b = Buffer.GetByte(ints, 2); // 0x03

解析:

(1) 首先將數(shù)組按元素索引序號大小作為高低位組合成一個 "大整數(shù)"。?
組合結果 : 0d0c0b0a 04030201?
(2) index 表示從低位開始的字節(jié)序號。右邊以 0 開始,index 2 自然是 0x03。

3. Buffer.SetByte: 設置數(shù)組內(nèi)存字節(jié)指定索引處的值。

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:將指定數(shù)目的字節(jié)從起始于特定偏移量的源數(shù)組復制到起始于特定偏移量的目標數(shù)組。

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

  • src:源緩沖區(qū)。
  • srcOffset:src 的字節(jié)偏移量。
  • dst:目標緩沖區(qū)。
  • dstOffset:dst 的字節(jié)偏移量。
  • count:要復制的字節(jié)數(shù)。

例一:arr的數(shù)組中字節(jié)0-16的值復制到字節(jié)12-28:(int占4個字節(jié)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 個字節(jié),從由往左,那么應該是 "0c 0b"。?
(2) 寫入 dst 位置 2,那么結果應該是 "00000002 0c0b0001"。?
(3) ints = { 0x0c0b0001, 0x00000002 },符合程序運行結果。

原文鏈接:https://www.cnblogs.com/springsnow/p/9428671.html

欄目分類
最近更新