C#按十六进制值将byte []拆分为新的byte []数组 [英] C# Split byte[] by hexademimal value into new array of byte[]

查看:249
本文介绍了C#按十六进制值将byte []拆分为新的byte []数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从IP数据包中获取数据,该IP数据包是字节数组,并将其拆分为以0x47开头的字节数组的集合,即

I want to take data from an IP packet which is a byte array and split it into a collection of byte arrays that start with 0x47 i.e. mpeg-2 transport packets.

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

For example the original byte array looks like this:

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

如何分割0x47上的字节数组并保留分隔符0x47,所以看起来像这样?顺序单词是从特定十六进制开始的字节数组的数组吗?

How would you split the byte array on 0x47 and retain the deliminator 0x47 so it looks like this? In order words an array of byte arrays that start on a particular hexadecimal?

[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

推荐答案

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

You can easily implement the splitter required:

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

这篇关于C#按十六进制值将byte []拆分为新的byte []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆