首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# -多维BitArray

C# -多维BitArray
EN

Stack Overflow用户
提问于 2014-05-18 10:04:51
回答 2查看 3.2K关注 0票数 0

我正在尝试使用多维BitArray,但我被如何用它设置或读取位所困扰。

使用普通的一维BitArray,我可以简单地执行以下操作来设置一点:

代码语言:javascript
复制
bitArray.Set(0, true);

然而,我不知道如何对二维位数组做同样的事情。例如,下面的代码没有意义,因为Set方法需要一个索引,但我之前已经在"0,0“中提供了索引:

代码语言:javascript
复制
    bitArray[0, 0].Set(0, true);

我的问题:制作和使用多维BitArray的正确方法是什么

EN

回答 2

Stack Overflow用户

发布于 2014-05-18 10:11:18

CLR而言,BitArray的实例不是数组(也就是说,BitArray不是“数组类型”)。如果你想存储2维比特信息,你有几个选择(我的所有例子都创建了一个10x20的2D卷):

a)使用单个BitArray数组,如下所示:

代码语言:javascript
复制
// Init:
BitArray[] storage = new BitArray[ 20 ];
for(int y=0;y<storage.Length;y++) storage[y] = new BitArray( 10, true );

// Usage:
Boolean at5x7 = storage[7][5];

b)使用BitArray本身作为2D空间,通过行和列索引(这实际上会更快,因为CLR不会频繁地调用其边界检查):

代码语言:javascript
复制
// Init:
const Int32 width = 10, height = 20;
BitArray storage = new BitArray( width * height );

// Usage:
Boolean at5x7 = storage[ (5 * width) + 7];
票数 8
EN

Stack Overflow用户

发布于 2019-09-29 05:20:42

代码语言:javascript
复制
public sealed class BitArray2D
{
    private BitArray _array;
    private int _dimension1;
    private int _dimension2;

    public BitArray2D(int dimension1, int dimension2)
    {
        _dimension1 = dimension1 > 0 ? dimension1 : throw new ArgumentOutOfRangeException(nameof(dimension1), dimension1, string.Empty);
        _dimension2 = dimension2 > 0 ? dimension2 : throw new ArgumentOutOfRangeException(nameof(dimension2), dimension2, string.Empty);
        _array = new BitArray(dimension1 * dimension2);
    }

    public bool Get(int x, int y) { CheckBounds(x, y); return _array[y * _dimension1 + x]; }
    public bool Set(int x, int y, bool val) { CheckBounds(x, y); return _array[y * _dimension1 + x] = val; }
    public bool this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } }

    private void CheckBounds(int x, int y)
    {
        if (x < 0 || x >= _dimension1)
        {
            throw new IndexOutOfRangeException();
        }
        if (y < 0 || y >= _dimension2)
        {
            throw new IndexOutOfRangeException();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23717880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档