在 C# 中使用分隔符连接字节数组
Joining byte arrays using a separator in C#
我想要类似于 String.Join(separator_string, list_of_strings)
的东西,但用于字节数组。
我需要它,因为我正在实现一个文件格式编写器,规范说
"Each annotation must be encoded as UTF-8 and separated by the ASCII byte 20
."
那么我需要这样的东西:
byte separator = 20;
List<byte[]> encoded_annotations;
joined_byte_array = Something.Join(separator, encoded_annotations);
我不相信有任何内置的东西,但写起来很容易。这是一个通用版本,但你可以让它只是字节数组很容易。
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 的数组),但一般的想法将适用于由字节数组组成的分隔符:
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();
}
}
您只需为加入命令指定所需的类型。
String.join<byte>(separator_string, list_of_strings);
我想要类似于 String.Join(separator_string, list_of_strings)
的东西,但用于字节数组。
我需要它,因为我正在实现一个文件格式编写器,规范说
"Each annotation must be encoded as UTF-8 and separated by the ASCII byte
20
."
那么我需要这样的东西:
byte separator = 20;
List<byte[]> encoded_annotations;
joined_byte_array = Something.Join(separator, encoded_annotations);
我不相信有任何内置的东西,但写起来很容易。这是一个通用版本,但你可以让它只是字节数组很容易。
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 的数组),但一般的想法将适用于由字节数组组成的分隔符:
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();
}
}
您只需为加入命令指定所需的类型。
String.join<byte>(separator_string, list_of_strings);