Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining byte arrays using a separator in C#

I want something similar to String.Join(separator_string, list_of_strings) but for byte arrays.

I need it because I am implementing a file format writer, and the specification says

"Each annotation must be encoded as UTF-8 and separated by the ASCII byte 20."

Then I would need something like:

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

joined_byte_array = Something.Join(separator, encoded_annotations);
like image 988
heltonbiker Avatar asked Oct 31 '25 17:10

heltonbiker


1 Answers

I don't believe there's anything built in, but it's easy enough to write. Here's a generic version, but you could make it do just byte arrays easily enough.

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;
}
like image 95
Jon Skeet Avatar answered Nov 03 '25 08:11

Jon Skeet