C#如何将字节添加到字节数组中

27
如何将一个字节添加到现有字节数组的开头? 我的目标是将长度为3字节的数组扩展到4个字节。因此,我需要在数组开头添加00填充。
8个回答

51

你不能这样做。无法调整数组大小。你必须创建一个新的数组并将数据复制到其中:

bArray = AddByteToArray(bArray,  newByte);

代码:

public byte[] AddByteToArray(byte[] bArray, byte newByte)
{
    byte[] newArray = new byte[bArray.Length + 1];
    bArray.CopyTo(newArray, 1);
    newArray[0] = newByte;
    return newArray;
}

9
Array.Resize(ref bArray, bArray.Length+1) - Ma Dude

23

正如这里许多人所指出的那样,C#中的数组以及大多数其他常见语言中的数组都具有静态大小。如果您正在寻找类似于PHP数组的东西,我猜想您可能正在寻找这样的东西,因为它是一种拥有动态大小(和类型!)数组的流行语言,那么您应该使用ArrayList:

var mahByteArray = new ArrayList<byte>();

如果你有一个从其他地方获取的字节数组,你可以使用 AddRange 函数。

mahByteArray.AddRange(mahOldByteArray);

然后您可以使用Add()和Insert()添加元素。

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

需要将其转换为数组吗?.ToArray() 可以帮助你完成!

mahOldByteArray = mahByteArray.ToArray();

1
ArrayList 如何使用类型参数? - CRice
4
FYI ArrayList已过时,推荐使用List<T>。除非必须与使用ArrayList的旧API进行交互,否则不应在针对.NET >= 2.0的新代码中使用ArrayList。 - John
https://dev59.com/25Xfa4cB1Zd3GeqPhZvD - hey

6
为了防止每次复制数组都非常低效,尝试使用 Stack:
var i = new Stack<byte>();
i.Push(1);
i.Push(2);
i.Push(3);

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

输出:

3
2
1

如果你需要一个数组,总是可以使用 ToArray 扩展方法。 - Matt Ellen

6

数组大小无法调整,因此您需要分配一个更大的新数组,在其开头写入新字节,并使用Buffer.BlockCopy()将旧数组的内容传输到新数组中。


2
Array.Resize() 怎么样? - Beygi
@Begyi:Array.Resize 不会为您在新数组的开头插入新字节,因此您仍需要将整个缓冲区向上复制一个字节以插入数据,导致数据被复制两次 - 因此对于这个特定的问题,它是低效的。但是,如果您希望“附加”新字节,则可以使用 Array.Resize。 - Jason Williams

3

尽管在内部它创建了一个新的数组并将值复制到其中,但您可以使用Array.Resize<byte>()使代码更易读。此外,根据您尝试实现的内容,您可能需要考虑检查MemoryStream类。


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

1
简单,只需像我一样使用下面的代码:

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

你能再解释一下这个做什么吗? - Alejandro
因此,第一个函数首先获取目标数组的长度,然后调整大小以便它可以容纳自己的数据和新添加的数据。然后逐字节将源数组中的所有内容添加到目标数组中。(通过调整大小引用新添加的字节,并更改其值以匹配源数组)第二个函数类似,但仅用于追加1个字节,而不是数组。它调整目标数组的大小,以便它可以容纳自己的数据和新字节,然后引用目标数组的末尾,并将新字节添加进去。 - Topaz M. Whitelock

0

我认为这是一个更完整的函数

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接