The BitArray in the System.Collections namespace is equivalent to an array of type bool bool[]. MSDN used BitArray as an example to implement an indexer, today studied this example, made some changes to the original implementation, the >> 5 operation into MoD 32, glad thought it would look more intuitive.
The code is as follows:
public class MyBitArray
{
private int[] m_Bits;
private int m_Length;
public MyBitArray(int length)
{
//Comment 1
m_Length = (length - 1) / 32 + 1;
m_Bits = new int[m_Length];
}
public bool this[int index]
{
//Comment 2
get { return (m_Bits[index / 32] & 1 << index) != 0; }
set
{
if (value)
m_Bits[index / 32] |= 1 << index;
else
m_Bits[index / 32] &= ~(1 << index);
}
}
}
Comment 1:1 int occupies 4 bytes and can store 32 bit values. So the actual length of the array of int required is 1/32 of the incoming length. The length-1 is to take into account the boundary value 32, (32-1)/32 + 1 = 1, otherwise the result is 2, and at this time only 1 int length of memory can be. And for the boundary value of 0, (0-1)/32 + 1 = 1, there is no problem.
A series of bit values in the Comment 2:bitarray can be considered segmented into the int element, and INDEX/32 takes out the int element that contains the bit value for the index. Then move the 1 to the appropriate bit to perform and/or operate. Looks a bit like the concept of memory access to the middle and page.
About indexers: The biggest difference between indexers and property is that the property only has a set method with parameters, and indexer get and set methods have default parameter index. In addition, the property can be static, the indexer of course not. Please see here for a detailed comparison.
About bitwise operations: Typically, when the specified number of bits of movement overflows, the displacement operation automatically models the number of bits moved. This is why the 1 << index in the set method above can move 1 to the correct position.
For example, 8 >> 33; Equivalent to 8 >> 1, the result is 4, not 0.
1 << 32; Equivalent to 1 << 0, the result is 1.
Interestingly, when the variable type is byte or short or int, the divisor for the CLR modulo is 32, not the length of the data type. Like what:
Short B = 1; b <<= 16;
The results obtained were 0. The CLR is not modulo 16 at this time.
However, if the data is defined as long, the divisor of the modulo is automatically changed to 64.
Long L = 1; L <<= 32; The resulting value is 4294967296, or 2^32.