Сведения о вопросе

Gaukhar

18:57, 4th August, 2020

Теги

c#   arrays   split    

Как split байтовый массив

Просмотров: 441   Ответов: 7

У меня есть массив байтов в памяти, считанный из файла. Я хотел бы split байтовый массив в определенной точке (индекс) без необходимости просто создавать новый байтовый массив и копировать каждый байт за один раз, увеличивая в памяти отпечаток ноги операции. Чего бы мне хотелось, так это что-то вроде этого:

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



  Сведения об ответе

dumai

05:07, 18th August, 2020

К ВАШЕМУ СВЕДЕНИЮ. Структура System.ArraySegment<T> в основном совпадает с ArrayView<T> в приведенном выше коде. Вы можете использовать эту структуру out-of-the-box таким же образом, если хотите.


  Сведения об ответе

baggs

20:41, 7th August, 2020

В C# с Linq вы можете сделать это:

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


  Сведения об ответе

PIRLO

16:37, 7th August, 2020

Вот как бы я это сделал:

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


  Сведения об ответе

$DOLLAR

04:50, 16th August, 2020

Попробуй вот это:

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


  Сведения об ответе

appple

22:07, 13th August, 2020

Я не совсем понимаю что ты имеешь в виду:

Я хотел бы split байтовый массив в определенной точке (индекс) без необходимости просто создавать новый байтовый массив и копировать каждый байт за один раз, увеличивая в памяти отпечаток ноги операции.

В большинстве языков, конечно, C#, как только массив был выделен, нет никакого способа изменить его размер. Похоже, вы ищете способ изменить длину массива, но это невозможно. Вы также хотите каким-то образом переработать память для второй части массива, чтобы создать второй массив, что вы также не можете сделать.

Вкратце: просто создайте новый массив.


  Сведения об ответе

9090

13:34, 18th August, 2020

То, что вам может понадобиться, - это сохранить начальную точку и количество элементов; по сути, построить итераторы. Если это C++, вы можете просто использовать std::vector<int> и использовать встроенные.

В C#, я бы построил небольшой класс итератора, который содержит начальный индекс, счетчик и реализует IEnumerable<> .


  Сведения об ответе

baggs

08:13, 28th August, 2020

Как сказал Эрен, вы можете использовать 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);
    }
}


Ответить на вопрос

Чтобы ответить на вопрос вам нужно войти в систему или зарегистрироваться