Pergunta

Eu tenho uma matriz de bytes na memória, lida de um arquivo.Eu gostaria de dividir a matriz de bytes em um determinado ponto (índice) sem ter que apenas criar uma nova matriz de bytes e copiar cada byte por vez, aumentando o espaço de memória da operação.O que eu gostaria é algo assim:

byte[] largeBytes = [1,2,3,4,5,6,7,8,9];  
byte[] smallPortion;  
smallPortion = split(largeBytes, 3);  

smallPortion seria igual a 1,2,3,4
largeBytes seria igual a 5,6,7,8,9

Foi útil?

Solução

É assim que eu faria isso:

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();
    }
}

Outras dicas

PARA SUA INFORMAÇÃO. System.ArraySegment<T> estrutura é basicamente a mesma coisa que ArrayView<T> no código acima.Você pode usar essa estrutura pronta para uso da mesma maneira, se desejar.

Em C# com Linq você pode fazer isso:

smallPortion = largeBytes.Take(4).ToArray();
largeBytes = largeBytes.Skip(4).Take(5).ToArray();

;)

Tente este:

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;
        }
    }

Não tenho certeza do que você quer dizer com:

Eu gostaria de dividir a matriz de bytes em um determinado ponto (índice) sem ter que apenas criar uma nova matriz de bytes e copiar cada byte por vez, aumentando o espaço de memória da operação.

Na maioria das linguagens, certamente C#, uma vez alocado um array, não há como alterar seu tamanho.Parece que você está procurando uma maneira de alterar o comprimento de um array, o que não é possível.Você também deseja reciclar de alguma forma a memória da segunda parte do array, para criar um segundo array, o que também não pode ser feito.

Resumindo:basta criar uma nova matriz.

Como Eren disse, você pode usar ArraySegment<T>.Aqui está um método de extensão e um exemplo de uso:

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);
    }
}

Você não pode.O que você pode querer é manter um ponto de partida e um número de itens;em essência, construa iteradores.Se for C++, você pode simplesmente usar std::vector<int> e use os integrados.

Em C#, eu construiria uma pequena classe iteradora que contém índice inicial, contagem e implementa IEnumerable<>.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top