简体   繁体   English

如何从字节数组的特定索引中删除字节

[英]How to remove bytes from a specific index from a byte array

I have a byte array . 我有一个字节数组。 I need to remove the bytes at specific index and split the byte arrays. 我需要删除特定索引处的字节并拆分字节数组。 For example Say I have a byte array of length 1000 . 例如,说我有一个长度为1000的字节数组。 And I need to remove the bytes from position 50 to 200 .So my expected result would be 2 byte arrays . 而且我需要从位置50到200中删除字节。所以我的预期结果将是2个字节数组。 One is 0-49 and another is 201-1000. 一个是0-49,另一个是201-1000。

Is Array.RemoveAt the only way to remove the byte array with index? Array.RemoveAt是删除带有索引的字节数组的唯一方法吗?

Thanks in advance! 提前致谢!

If speed is critical, you can create two new arrays and use Array.Copy() to copy the required bytes into them. 如果速度至关重要,则可以创建两个新的数组,然后使用Array.Copy()将所需的字节复制到它们中。

To make this easier to use, it might be more convenient to write a little extension method for arrays which extracts and returns a subset, like this (note: error handling omitted for brevity): 为了使它更易于使用,为数组编写一些扩展方法以提取并返回一个子集可能会更方便,如下所示(注意:为简便起见,省略了错误处理):

public static class ArrayExt
{
    public static T[] Subset<T>(this T[] array, int start, int count)
    {
        T[] result = new T[count];
        Array.Copy(array, start, result, 0, count);
        return result;
    }
}

Then you can use it like so (I have corrected the index from your example; you had it starting at 201, but it should have been 200): 然后,您可以像这样使用它(我已经纠正了示例中的索引;您从201开始,但是应该为200):

var array1 = new byte[1000];

// ... populate array1 somehow, then extract subsets like so:

var array2 = array1.Subset(  0,  50);
var array3 = array1.Subset(200, 800);

// Now array2 and array3 are two byte arrays 
// containing the required bytes.

This is probably the fastest you are likely to get. 这可能是最快的速度。

You could use IEnumerable Take and Skip , for example 例如,您可以使用IEnumerable TakeSkip

byte[] origin = new byte[200];
for(int i = 0; i < origin.Length; i++)
    origin[i] = (byte)i;

byte[] first = origin.Take(50).ToArray();
byte[] second = origin.Skip(100).Take(50).ToArray();

Below code can be used to split the byte array, "index" starting index and "count" is the index count upto which index you want to split, here for your condition index=50 and count is 150; 下面的代码可用于拆分字节数组,“索引”起始索引,“计数”是您要拆分的索引数,此处条件为index = 50并且count为150;

List<byte> byteArray = array.ToList(); //array is the byte array
byteArray.RemoveRange(index, count);
Byte[] array1 = byteArray.ToArray(); //array1 is the resultant byte array

Cant you get the sub arrays like this? 不能得到像这样的子数组吗?

byte[] array1 = array.ToList().GetRange(0, x1-1).ToArray();
byte[] array2 = array.ToList().GetRange(x2, array.Length- x2 - 1).ToArray();

where x1 and x2 is 50 and 200 in your example 在您的示例中x1和x2分别是50和200

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

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