c# how to add byte to byte array

前端 未结 6 632
梦毁少年i
梦毁少年i 2020-12-08 15:30

How to add a byte to the beginning of an existing byte array? My goal is to make array what\'s 3 bytes long to 4 bytes. So that\'s why I need to add 00 padding in the beginn

6条回答
  •  无人及你
    2020-12-08 16:04

    Simple, just use the code below, as I do:

            public void AppendSpecifiedBytes(ref byte[] dst, byte[] src)
        {
            // Get the starting length of dst
            int i = dst.Length;
            // Resize dst so it can hold the bytes in src
            Array.Resize(ref dst, dst.Length + src.Length);
            // For each element in src
            for (int j = 0; j < src.Length; j++)
            {
                // Add the element to dst
                dst[i] = src[j];
                // Increment dst index
                i++;
            }
        }
    
        // Appends src byte to the dst array
        public void AppendSpecifiedByte(ref byte[] dst, byte src)
        {
            // Resize dst so that it can hold src
            Array.Resize(ref dst, dst.Length + 1);
            // Add src to dst
            dst[dst.Length - 1] = src;
        }
    

提交回复
热议问题