将system.collections.bitarray分成每个32位的子位数组 [英] dividing system.collections.bitarray into sub bitarrays of 32 bits each

查看:23
本文介绍了将system.collections.bitarray分成每个32位的子位数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网上搜索过,但没有得到我真正需要的东西.我有一个大小为15,936的位数组.我需要将此位数组划分为位数组列表,每个位数组具有32位(15936/32 = 498位数组列表).

I have searched in net but not getting exactly what I need. I have a bitarray of size 15,936. I need to divide this bit array into list of bitarrays , with each bit array having 32 bits(15936/32 = 498 bitarray list).

无法确切找到如何分割位数组.请帮忙.

Not able to find exactly how to divide bitarray. Please do help.

谢谢

推荐答案

首先需要32位值使此操作非常容易,因为您可以将其复制到 int [] ,然后每个 int 创建一个 BitArray ,通过创建一个单元素 int 数组传递数据:

The first that you want 32-bit values makes this pretty easy, because you can copy it to an int[], then create one BitArray per int, passing the data by creating a single-element int array:

int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
var smallBitArrays = values.Select(v => new BitArray(new[] { v })).ToList();

或更有效地,为每次迭代重用相同的 int [] :

Or more efficiently, reusing the same int[] for each iteration:

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();

如果这些给您的位数组与您期望的顺序相反,只需在 CopyTo 调用后调用 Array.Reverse(values).

If those give you the bit arrays in the opposite order to what you expect, just call Array.Reverse(values) after the CopyTo call.

遗憾的是, BitArray 没有构造函数采用现有的数组,偏移量和计数...这将大大提高其效率.(当然,切片复制"操作也会如此.)

It's a pity that BitArray doesn't have a constructor taking an existing array, offset and count... that would make it significantly more efficient. (As would a "slice copy" operation, of course.)

一个更通用的选择是为该切片副本"部分创建一个扩展方法:

A more general purpose option would be to create an extension method precisely for that "slice copy" part:

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;
}

然后:

var smallBitArrays = Enumerable
    .Range(0, bigBitArray.Length / 32)
    .Select(offset => bigBitArray.CopySlice(offset * 32, 32))
    .ToList();

这篇关于将system.collections.bitarray分成每个32位的子位数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆