阅读量:0
在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功能,包括设置和获取位。你可以根据需要扩展此类,添加更多的方法,如按位操作、转换为字符串等。