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

如何在现有字节数组的开头添加一个字节? 我的目标是使数组长3个字节到4个字节。 所以这就是为什么我需要在它的开头添加00填充。

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

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

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

 var mahByteArray = new ArrayList(); 

如果您有来自其他地方的字节数组,则可以使用AddRange函数。

 mahByteArray.AddRange(mahOldByteArray); 

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

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

需要它回到arrays? .ToArray()让你满意!

 mahOldByteArray = mahByteArray.ToArray(); 

数组无法resize,因此您需要分配一个较大的新数组,在其开头写入新字节,并使用Buffer.BlockCopy传输旧数组的内容。

为了防止每次重新复制数组效率不高

怎么样使用Stack

 csharp> var i = new Stack(); csharp> i.Push(1); csharp> i.Push(2); csharp> i.Push(3); csharp> i; { 3, 2, 1 } csharp> foreach(var x in i) { > Console.WriteLine(x); > } 

3 2 1

虽然在内部它创建了一个新数组并将值复制到其中,但您可以使用Array.Resize()来获得更易读的代码。 您也可以考虑根据您要实现的目标来检查MemoryStream类。

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

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