怎样在C#里操作BitSet数据结构

   2024-09-30 8140
核心提示:在C#中,没有内置的BitSet数据结构using System;using System.Collections;public class BitSet : ICollection{private readonly

在C#中,没有内置的BitSet数据结构

using System;using System.Collections;public class BitSet : ICollection{    private readonly byte[] data;    public BitSet(int size)    {        if (size < 0)            throw new ArgumentException("Size cannot be negative", nameof(size));        data = new byte[(size + 7) / 8];    }    public bool this[int index]    {        get => Get(index);        set => Set(index, value);    }    public bool Get(int index)    {        CheckIndex(index);        int byteIndex = index / 8;        int bitIndex = index % 8;        return (data[byteIndex] & (1<< bitIndex)) != 0;    }    public void Set(int index, bool value)    {        CheckIndex(index);        int byteIndex = index / 8;        int bitIndex = index % 8;        if (value)            data[byteIndex] |= (byte)(1<< bitIndex);        else            data[byteIndex] &= (byte)~(1<< bitIndex);    }    private void CheckIndex(int index)    {        if (index < 0 || index >= data.Length * 8)            throw new ArgumentOutOfRangeException(nameof(index), "Index out of range");    }    // ICollection implementation    public int Count => data.Length * 8;    public bool IsSynchronized => false;    public object SyncRoot => this;    public void CopyTo(Array array, int index)    {        if (array == null)            throw new ArgumentNullException(nameof(array));        if (index < 0)            throw new ArgumentOutOfRangeException(nameof(index), "Index cannot be negative");        if (array.Length - index< Count)            throw new ArgumentException("Destination array is not large enough");        for (int i = 0; i< Count; i++)            array.SetValue(Get(i), index + i);    }    public IEnumerator GetEnumerator()    {        for (int i = 0; i< Count; i++)            yield return Get(i);    }}

使用示例:

var bitSet = new BitSet(10);bitSet[3] = true;bitSet[5] = true;for (int i = 0; i < bitSet.Count; i++)    Console.WriteLine($"Bit {i}: {bitSet[i]}");

这个实现提供了基本的BitSet功能,包括设置和获取位。你可以根据需要扩展此类,添加更多的方法,如按位操作、转换为字符串等。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号