C#将十六进制值的byte []拆分为byte []的新数组

时间:2016-06-24 19:14:02

标签: c# mpeg2-ts

我想从一个字节数组的IP数据包中获取数据并将其拆分为以0x47开头的字节数组集合,即mpeg-2 transport packets.

例如,原始字节数组如下所示:

08 FF FF 47 FF FF FF 47 FF FF 47 FF 47 FF FF FF FF 47 FF FF 

如何在0x47上拆分字节数组并保留分隔符0x47,使它看起来像这样?顺序是一个以特定十六进制开始的字节数组数组?

[0] 08 FF FF
[1] 47 FF FF FF
[2] 47 FF FF
[3] 47 FF
[4] 47 FF FF FF FF
[5] 47 FF FF

4 个答案:

答案 0 :(得分:3)

您可以轻松实现所需的拆分器:

public static IEnumerable<Byte[]> SplitByteArray(IEnumerable<Byte> source, byte marker) {
  if (null == source)
    throw new ArgumentNullException("source");

  List<byte> current = new List<byte>();

  foreach (byte b in source) {
    if (b == marker) {
      if (current.Count > 0)
        yield return current.ToArray();

      current.Clear();
    }

    current.Add(b);
  }

  if (current.Count > 0)
    yield return current.ToArray();
}

并使用它:

  String source = "08 FF FF 47 FF FF FF 47 FF FF 47 FF 47 FF FF FF FF 47 FF FF";

  // the data
  Byte[] data = source
    .Split(' ')
    .Select(x => Convert.ToByte(x, 16))
    .ToArray();

  // splitted
  Byte[][] result = SplitByteArray(data, 0x47).ToArray();

  // data splitted has been represented for testing
  String report = String.Join(Environment.NewLine, 
    result.Select(line => String.Join(" ", line.Select(x => x.ToString("X2")))));

  // 08 FF FF
  // 47 FF FF FF
  // 47 FF FF
  // 47 FF
  // 47 FF FF FF FF
  // 47 FF FF
  Console.Write(report);

答案 1 :(得分:2)

可能的解决方案:

byte[] source = // ...
string packet = String.Join(" ", source.Select(b => b.ToString("X2")));

// chunks is of type IEnumerable<IEnumerable<byte>>
var chunks = Regex.Split(packet, @"(?=47)")
             .Select(c =>
                 c.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(x => Convert.ToByte(x, 16)));

答案 2 :(得分:1)

有几种方法可以做到这一点,最简单的方法是使用.Split()并替换正在拆分的值。

string[] values = packet.Split("47");
for(int i = 0; i < values.Length; i++)
{
    Console.WriteLine("[{0}] 47 {1}", i, values[i]);
    // C# 6+ way: Console.WriteLine($"[{i}] 47 {values[i]}");
}

当然,你总是可以使用正则表达式,但我的正则表达式技能非常有限,我不认为我可以亲自构建一个有效的正则表达式。

答案 3 :(得分:1)

对你来说可能有点过于苛刻,但应该可以正常工作:

string ins = "08 FF FF 47 FF FF FF 47 FF FF 47 FF 47 FF FF FF FF 47 FF FF ";
string[] splits = ins.Split(new string[] { "47" }, StringSplitOptions.None);
for (int i = 0; i < splits.Length; i++) {
     splits[i] = "47 " + splits[i];
}

编辑:类似于我现有的答案。

相关问题