You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#将数组拆分为以特定值开头的多个子数组?

解决方案

实现思路

  1. 遍历原字节数组,定位所有0xAA的起始索引;
  2. 对每个起始索引,确定子数组的结束位置:若为最后一个起始点则到数组末尾,否则到下一个0xAA的前一位;
  3. 根据起始和结束索引提取子数组,收集所有符合要求的结果。

代码示例

byte[] bytes = new byte[9];
bytes[0] = 0x1a;
bytes[1] = 0xAA;
bytes[2] = 0xab;
bytes[3] = 0xad;
bytes[4] = 0xAA;
bytes[5] = 0x01;
bytes[6] = 0x02;
bytes[7] = 0xAA;
bytes[8] = 0xac;

List<byte[]> splitResult = new List<byte[]>();
List<int> startPositions = new List<int>();

// 收集所有0xAA的起始位置
for (int i = 0; i < bytes.Length; i++)
{
    if (bytes[i] == 0xAA)
    {
        startPositions.Add(i);
    }
}

// 拆分生成子数组
for (int i = 0; i < startPositions.Count; i++)
{
    int start = startPositions[i];
    // 计算当前子数组的结束索引
    int end = i == startPositions.Count - 1 ? bytes.Length - 1 : startPositions[i + 1] - 1;
    int subLength = end - start + 1;

    byte[] subArray = new byte[subLength];
    Array.Copy(bytes, start, subArray, 0, subLength);
    splitResult.Add(subArray);
}

// 输出验证
foreach (var arr in splitResult)
{
    Console.WriteLine(string.Join(", ", arr.Select(b => $"0x{b:X2}")));
}

代码说明

  • 先通过循环定位所有0xAA的位置,作为子数组的起始点;
  • 处理每个起始点时,通过判断是否为最后一个起始点来确定子数组的结束位置,避免数组越界;
  • 使用Array.Copy高效复制子数组,若偏好LINQ写法,也可替换为bytes.Skip(start).Take(subLength).ToArray(),但前者处理大数组时性能更优;
  • 遍历结果列表即可得到拆分后的所有目标子数组,输出格式与需求一致。

内容的提问来源于stack exchange,提问作者Dominota

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:22:10