简体   繁体   English

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

[英]c# how to add byte to byte array

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.我的目标是使数组长度为 3 个字节到 4 个字节。 So that's why I need to add 00 padding in the beginning of it.所以这就是为什么我需要在它的开头添加 00 填充。

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

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized.正如这里的许多人指出的那样,C# 以及大多数其他常见语言中的数组都是静态大小的。 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:如果您正在寻找更像 PHP 数组的东西,我猜您就是这样,因为它是一种具有动态大小(和类型)数组的流行语言:您应该使用 ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.如果您有来自其他地方的字节数组,则可以使用 AddRange 函数。

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.然后您可以使用 Add() 和 Insert() 添加元素。

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! .ToArray() 有你覆盖!

mahOldByteArray = mahByteArray.ToArray();

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.数组不能调整大小,所以你需要分配一个更大的新数组,在它的开头写入新字节,然后使用 Buffer.BlockCopy 来传输旧数组的内容。

To prevent recopy the array every time which isn't efficient为了防止每次都重新复制数组效率不高

What about using Stack使用 Stack 怎么样

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 3 2 1

Although internally it creates a new array and copies values into it, you can use Array.Resize<byte>() for more readable code.尽管它在内部创建了一个新数组并将值复制到其中,但您可以使用Array.Resize<byte>()以获得更具可读性的代码。 Also you might want to consider checking the MemoryStream class depending on what you're trying to achieve.此外,您可能需要考虑根据您要实现的目标来检查MemoryStream类。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM