如何分割字节数组
时间:2020-03-05 18:41:43 来源:igfitidea点击:
我在内存中有一个字节数组,可从文件中读取。我想在某个点(索引)拆分字节数组,而不必只创建一个新的字节数组并一次复制每个字节,从而增加了该操作在内存中的占用空间。我想要的是这样的:
byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3);
smallPortion
等于1,2,3,4largeBytes
等于5,6,7,8,9
解决方案
回答
你不能我们可能想要的是保持起点和物品数量;本质上,构建迭代器。如果是C ++,则可以使用std :: vector <int>
并使用内置的。
在C#中,我将构建一个小的迭代器类,该类包含开始索引,计数并实现IEnumerable <>。
回答
这就是我要做的:
using System; using System.Collections; using System.Collections.Generic; class ArrayView<T> : IEnumerable<T> { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator<T> GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator<T> enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5); ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } }
回答
我不确定意思是:
I would like to split the byte array at a certain point(index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation.
在大多数语言(当然是C#)中,一旦分配了数组,就无法更改其大小。听起来我们正在寻找一种更改数组长度的方法,但是我们不能这样做。我们还想以某种方式回收数组第二部分的内存,以创建第二个数组,我们也不能这样做。
总结:只需创建一个新数组即可。
回答
供参考。 System.ArraySegment <T>的结构基本上与上面代码中的ArrayView <T>相同。我们可以根据需要使用相同的开箱即用结构。