How to split a byte array

前端 未结 7 1824
一个人的身影
一个人的身影 2020-12-03 20:20

I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy eac

7条回答
  •  心在旅途
    2020-12-03 21:12

    This is how I would do that:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    
    class ArrayView : IEnumerable
    {
        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 GetEnumerator()
        {
            for (int i = offset; i < offset + count; i++)
                yield return array[i];
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            IEnumerator 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 p1 = new ArrayView(arr, 0, 5);
            ArrayView p2 = new ArrayView(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();
        }
    }
    

提交回复
热议问题