How to split a byte array

前端 未结 7 1761
一个人的身影
一个人的身影 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:26

    As Eren said, you can use ArraySegment<T>. Here's an extension method and usage example:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题