// From the ECMA-334 C# Language specifications (section 17.8).
// Also in Hejlsberg et al., The C# Programming Language, 2ed.
using System;
public class BitArray
{
int[] bits;
int length;
public BitArray(int length) {
if (length < 0) throw new ArgumentException();
bits = new int[((length - 1) >> 5) + 1];
this.length = length;
}
public int Length {
get { return length; }
}
public bool this[int index] {
get {
if (index < 0 || index >= length) {
throw new IndexOutOfRangeException();
}
return (bits[index >> 5] & 1 << index) != 0;
}
set {
if (index < 0 || index >= length) {
throw new IndexOutOfRangeException();
}
if (value) {
bits[index >> 5] |= 1 << index;
}
else {
bits[index >> 5] &= ~(1 << index);
}
}
}
} | |
For more comprehensive explanation, see
the text book version of this material.
Implicitly private instance variables.
new[...] creates a relatively short array, which
is initialized to 0 (the default integer value).
The indexer.
The getter.
If index is in range
... return the bit as a boolean value.
The setter.
If index is in range
If value is true
... set the appropriate bit to 1
else set the bit to 0.
|