In C# how can I truncate a byte[] array

后端 未结 6 711
太阳男子
太阳男子 2021-01-03 18:27

I have a byte[] array of one size, and I would like to truncate it into a smaller array?

I just want to chop the end off.

相关标签:
6条回答
  • 2021-01-03 18:39

    By the way, Array.Resize method takes much more time to complete. In my simple case, I just needed to resize array of bytes (~8000 items to ~20 items):

    1. Array.Resize // 1728 ticks
    2. Array.Copy // 8 ticks
    0 讨论(0)
  • 2021-01-03 18:42

    You can't truncate an array in C#. They are fixed in length.

    If you want a data structure that you can truncate and acts like an array, you should use List<T>. You can use the List<T>.RemoveRange method to achieve this.

    0 讨论(0)
  • 2021-01-03 18:46

    You could use Array.Resize, but all this really does is make a truncated copy of the original array and then replaces the original array with the new one.

    0 讨论(0)
  • 2021-01-03 18:48

    Arrays are fixed-size in C# (.NET).

    You'll have to copy the contents to a new one.

    byte[] sourceArray = ...
    byte[] truncArray = new byte[10];
    
    Array.Copy(sourceArray , truncArray , truncArray.Length);
    
    0 讨论(0)
  • 2021-01-03 18:58
        private static void Truncate() {
    
            byte[] longArray = new byte[] {1,2,3,4,5,6,7,8,9,10};
    
            Array.Resize(ref longArray, 5);//longArray = {1,2,3,4,5}
    
            //if you like linq
            byte[] shortArray = longArray.Take(5).ToArray();
    
        }
    
    0 讨论(0)
  • I usually create an extension method:

     public static byte[] SubByteArray(this byte[] byteArray, int len)
        {
            byte[] tmp = new byte[len];
            Array.Copy(byteArray, tmp, len);
    
            return tmp;
        }
    

    Which can be called on the byte array easily like this:

    buffer.SubByteArray(len)
    
    0 讨论(0)
提交回复
热议问题