溫馨提示×

怎樣在C#里操作BitSet數(shù)據(jù)結(jié)構(gòu)

c#
小樊
85
2024-09-16 09:55:24
欄目: 編程語言

在C#中,沒有內(nèi)置的BitSet數(shù)據(jù)結(jié)構(gòu)

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]}");

這個實現(xiàn)提供了基本的BitSet功能,包括設(shè)置和獲取位。你可以根據(jù)需要擴展此類,添加更多的方法,如按位操作、轉(zhuǎn)換為字符串等。

0