如何将一个字节添加到现有字节数组的开头?
我的目标是将长度为3字节的数组扩展到4个字节。因此,我需要在数组开头添加00填充。
你不能这样做。无法调整数组大小。你必须创建一个新的数组并将数据复制到其中:
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<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();
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数组大小无法调整,因此您需要分配一个更大的新数组,在其开头写入新字节,并使用Buffer.BlockCopy()
将旧数组的内容传输到新数组中。
尽管在内部它创建了一个新的数组并将值复制到其中,但您可以使用Array.Resize<byte>()
使代码更易读。此外,根据您尝试实现的内容,您可能需要考虑检查MemoryStream
类。
var newArray = arrayToPrepend.Concat(array).ToArray();
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;
}
我认为这是一个更完整的函数
/// <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;
}
Array.Resize(ref bArray, bArray.Length+1)
- Ma Dude