第一个您想要 32 位值的操作非常简单,因为您可以将其复制到int[]
,然后创建一个BitArray
per int
,通过创建单个元素来传递数据int
array:
int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
var smallBitArrays = values.Select(v => new BitArray(new[] { v })).ToList();
或者更有效地重复使用相同的int[]
对于每次迭代:
int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
// Reuse this on every iteration, to avoid creating more arrays than we need.
// Somewhat ugly, but more efficient.
int[] buffer = new int[1];
var smallBitArrays = values.Select(v =>
{
buffer[0] = v;
return new BitArray(buffer))
}).ToList();
如果这些给你的位数组的顺序与你期望的相反,只需调用Array.Reverse(values)
之后CopyTo
call.
遗憾的是BitArray
没有采用现有数组、偏移量和计数的构造函数...这将使其效率显着提高。 (当然,就像“切片复制”操作一样。)
更通用的选项是为“切片复制”部分精确创建一个扩展方法:
public static BitArray CopySlice(this BitArray source, int offset, int length)
{
// Urgh: no CopyTo which only copies part of the BitArray
BitArray ret = new BitArray(length);
for (int i = 0; i < length; i++)
{
ret[i] = source[offset + i];
}
return ret;
}
Then:
var smallBitArrays = Enumerable
.Range(0, bigBitArray.Length / 32)
.Select(offset => bigBitArray.CopySlice(offset * 32, 32))
.ToList();