C#使用System.Buffer以字節(jié)數組Byte[]操作基元類型數據
1. Buffer.ByteLength:計算基元類型數組累計有多少字節(jié)組成。
該方法結果等于"基元類型字節(jié)長度 * 數組長度"
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 = 122. Buffer.GetByte:獲取數組內存中字節(jié)指定索引處的值。
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 表示從低位開始的字節(jié)序號。右邊以 0 開始,index 2 自然是 0x03。
3. Buffer.SetByte: 設置數組內存字節(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:將指定數目的字節(jié)從起始于特定偏移量的源數組復制到起始于特定偏移量的目標數組。
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é)數。
例一:arr的數組中字節(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 },符合程序運行結果。
到此這篇關于C#使用System.Buffer以字節(jié)數組Byte[]操作基元類型數據的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C#手動操作DataGridView使用各種數據源填充表格實例
本文主要介紹了C#手動操作DataGridView使用各種數據源填充表格實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

