Как разбить массив байтов
У меня есть байтовый массив в памяти, прочитанный из файла. Я хотел бы разбить массив байтов в определенной точке (индексе), не создавая новый массив байтов и не копируя каждый байт за один раз, увеличивая длину записи в памяти операции. Я бы хотел, чтобы это было так:
byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);
smallPortion
будет равно 1,2,3,4
largeBytes
будет равняться 5,6,7,8,9
Ответы
Ответ 1
Вот как я это сделал:
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();
}
}
Ответ 2
FYI. Структура System.ArraySegment<T>
в основном является тем же самым, что и ArrayView<T>
в коде выше. Вы можете использовать эту готовую структуру так же, если хотите.
Ответ 3
В С# с Linq вы можете сделать это:
smallPortion = largeBytes.Take(4).ToArray();
largeBytes = largeBytes.Skip(4).Take(5).ToArray();
;)
Ответ 4
Попробуйте следующее:
private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)
{
int bArrayLenght = bArray.Length;
byte[] bReturn = null;
int i = 0;
for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
{
bReturn = new byte[intBufforLengt];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
yield return bReturn;
}
int intBufforLeft = bArrayLenght - i * intBufforLengt;
if (intBufforLeft > 0)
{
bReturn = new byte[intBufforLeft];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
yield return bReturn;
}
}
Ответ 5
Я не уверен, что вы имеете в виду:
Я хотел бы разбить массив байтов на определенную точку (индекс), не имея необходимости просто создавать новый массив байтов и копировать каждый байт за раз, увеличивая печать в памяти в операции.
В большинстве языков, конечно же, С#, как только массив был выделен, нет способа изменить его размер. Похоже, вы ищете способ изменить длину массива, чего вы не можете. Вы также хотите как-то переработать память для второй части массива, чтобы создать второй массив, который вы также не можете сделать.
Вкратце: просто создайте новый массив.
Ответ 6
Вы не можете. Вы можете захотеть сохранить начальную точку и количество элементов; по сути, строить итераторы. Если это С++, вы можете просто использовать std::vector<int>
и использовать встроенные.
В С# я бы построил небольшой класс итератора, который содержит индекс начала, подсчет и реализует IEnumerable<>
.
Ответ 7
Как Эрен сказал, вы можете использовать ArraySegment<T>
. Здесь используется метод расширения и пример использования:
public static class ArrayExtensionMethods
{
public static ArraySegment<T> GetSegment<T>(this T[] arr, int offset, int? count = null)
{
if (count == null) { count = arr.Length - offset; }
return new ArraySegment<T>(arr, offset, count.Value);
}
}
void Main()
{
byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var p1 = arr.GetSegment(0, 5);
var p2 = arr.GetSegment(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);
}
}