【发布时间】:2011-04-08 06:33:50
【问题描述】:
如何在现有字节数组的开头添加一个字节? 我的目标是使数组长 3 个字节到 4 个字节。所以这就是为什么我需要在它的开头添加 00 填充。
【问题讨论】:
如何在现有字节数组的开头添加一个字节? 我的目标是使数组长 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;
}
【讨论】:
Array.Resize(ref bArray, bArray.Length+1)
正如这里的许多人所指出的,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();
【讨论】:
数组无法调整大小,因此需要分配一个更大的新数组,在其开头写入新字节,并使用 Buffer.BlockCopy 将旧数组的内容传输过去。
【讨论】:
为了防止每次都重新复制数组效率不高
如何使用堆栈
csharp> var i = new Stack<byte>();
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
【讨论】:
ToArray这个扩展方法。
虽然它在内部创建了一个新数组并将值复制到其中,但您可以使用Array.Resize<byte>() 以获得更易读的代码。此外,您可能需要考虑检查 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;
}
【讨论】:
我觉得是功能比较齐全的
/// <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;
}
【讨论】: