使用C#中的分隔符连接字节数组

时间:2015-03-16 17:15:28

标签: c# arrays byte concatenation

我想要类似于String.Join(separator_string, list_of_strings)但类似于字节数组的东西。

我需要它,因为我正在实现文件格式编写器,并且规范说

  

“每个注释必须编码为UTF-8,并以ASCII字节20分隔。”

然后我需要类似的东西:

byte separator = 20;
List<byte[]> encoded_annotations;

joined_byte_array = Something.Join(separator, encoded_annotations);

2 个答案:

答案 0 :(得分:3)

我不相信内置任何东西,但写起来很容易。这是一个通用版本,但您可以轻松地使字节数组。

public static T[] Join<T>(T separator, IEnumerable<T[]> arrays)
{
    // Make sure we only iterate over arrays once
    List<T[]> list = arrays.ToList();
    if (list.Count == 0)
    {
        return new T[0];
    }
    int size = list.Sum(x => x.Length) + list.Count - 1;
    T[] ret = new T[size];
    int index = 0;
    bool first = true;
    foreach (T[] array in list)
    {
        if (!first)
        {
            ret[index++] = separator;
        }
        Array.Copy(array, 0, ret, index, array.Length);
        index += array.Length;
        first = false;
    }
    return ret;
}

答案 1 :(得分:1)

我最终使用了这个,调整到我的特定情况,一个分隔符由一个单字节组成(而不是一个大小为1的数组),但一般的想法将适用于由字节数组组成的分隔符:

public byte[] ArrayJoin(byte separator, List<byte[]> arrays)
{
    using (MemoryStream result = new MemoryStream())
    {
        byte[] first = arrays.First();
        result.Write(first, 0, first.Length);

        foreach (var array in arrays.Skip(1))
        {
            result.WriteByte(separator);
            result.Write(array, 0, array.Length);
        }

        return result.ToArray();
    }
}
相关问题