29

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 beginning of it.

8 Answers 8

55

You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:

bArray = AddByteToArray(bArray,  newByte);

code:

public byte[] AddByteToArray(byte[] bArray, byte newByte)
{
    byte[] newArray = new byte[bArray.Length + 1];
    bArray.CopyTo(newArray, 1);
    newArray[0] = newByte;
    return newArray;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Array.Resize(ref bArray, bArray.Length+1)
23

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

3 Comments

How can ArrayList be used with type arguments?
FYI ArrayList is deprecated in favor of List<T>. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.
6

To prevent recopy the array every time which is inefficient, try using a Stack:

var i = new Stack<byte>();
i.Push(1);
i.Push(2);
i.Push(3);

foreach(var x in i) {
    Console.WriteLine(x);
}

Output:

3
2
1

1 Comment

And if you need an array, there is always the ToArray extension method.
6

Arrays can't be resized, so you need to allocte a new array that is larger, write the new byte at the beginning of it, and use Buffer.BlockCopy() to transfer the contents of the old array across.

2 Comments

How about Array.Resize()
@Begyi: Array.Resize will not insert the new byte at the beginning of the new array for you, so you will still need to copy the entire buffer up by one byte to insert the data, resulting in the data being copied twice - so for this particular question it would be inefficient. However, Array.Resize would be approriate if you wished to append the new byte.
3

Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>() for more readable code. Also you might want to consider checking the MemoryStream class depending on what you're trying to achieve.

Comments

3
var newArray = arrayToPrepend.Concat(array).ToArray();

Comments

1

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

2 Comments

Can you explain a bit more of what this does?
So, the first function first gets the length of the destination array, then resize it so that it can hold it's own data and the new, appended data. then adds everything on the source array, byte by byte, to the destination array. (Refers to newly added bytes by resize, changes their value to match the source array) The second function is similar, but is only used to append 1 byte, not an array. It resized the destionation array so that it can hold it's own data and the new byte, then it refers to the end of the destination array, and adds the new byte in.
0

I think it is a more complete function

/// <summary>
/// add a new byte to end or start of a byte array
/// </summary>
/// <param name="_input_bArray"></param>
/// <param name="_newByte"></param>
/// <param name="_add_to_start_of_array">if this parameter is True then the byte will be added to the beginning of array otherwise
/// to the end of the array</param>
/// <returns>result byte array</returns>
        public byte[] addByteToArray(byte[] _input_bArray, byte _newByte, Boolean _add_to_start_of_array)
        {
            byte[] newArray;
            if (_add_to_start_of_array)
            {
                newArray = new byte[_input_bArray.Length + 1];
                _input_bArray.CopyTo(newArray, 1);
                newArray[0] = _newByte;
            }
            else
            {
                newArray = new byte[_input_bArray.Length + 1];
                _input_bArray.CopyTo(newArray, 0);
                newArray[_input_bArray.Length] = _newByte;
            }
            return newArray;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.