我有一个字节数组,我想分割每个1字节的值。比如string.split。
例如:如果我的字节数组有这个数据:0x00,0x0A,0x02,0x0A,0X03,0x0A
b_arr0[0] = 0x00;
b_arr0[1] = 0x0a;
b_arr1[0] = 0x02;
b_arr1[1] = 0x0a;
b_arr2[0] = 0x03;
b_arr2[1] = 0x0a;
答案 0 :(得分:1)
如果要以与String.Split
类似的方式使用某个字节作为分隔符拆分字节数组,可以这样做:
public byte[][] Split(byte[] input, byte separator, bool ignoreEmptyEntries = false)
{
var subArrays = new List<byte[]>();
var start = 0;
for (var i = 0; i <= input.Length; ++i)
{
if (input.Length == i || input[i] == separator)
{
if (i - start > 0 || ignoreEmptyEntries)
{
var destination = new byte[i - start];
Array.Copy(input, start, destination, 0, i - start);
subArrays.Add(destination);
}
start = i + 1;
}
}
return subArrays.ToArray();
}
用法:
var bytes = new byte[]
{
0x00,
0x01,
0xaa, // Split here.
0x02,
0x03,
0xaa, // Split here.
0x04,
0x05
};
var splitted = Split(bytes, separator: 0xaa, ignoreEmptyEntries: true);
请注意,分隔符字节不包含在输出数组中。
答案 1 :(得分:0)
也许有这个LINQ查询?
byte[][] b_arr1 = data
.Select((b, ix) => new { Byte = b, Index = ix })
.GroupBy(x => x.Index / 2, x => x.Byte)
.Select(byteGroup => byteGroup.ToArray())
.ToArray();