السلام عليكم ورحمة الله وبركاته
لقد مر علي في أحد الكتب هذا الكود ، ولم أفهمة مع وجود الشرح له
فأرجوا من الإخوة تبسيطة لكي يتم فهمه
class BitArray
{
public BitArray(int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(...);
this.bits = new int[((length - 1) >> 5) + 1];
this.length = length;
}
public int Length
{
get { return length; }
}
public bool this[int index]
{
get {
BoundsCheck(index);
return (bits[index >> 5] & (1 << index)) != 0;
}
set {
BoundsCheck(index);
if (value) {
bits[index >> 5] |= (1 << index);
} else {
bits[index >> 5] &= ~(1 << index);
}
}
}
private void BoundsCheck(int index)
{
if (index < 0 || index >= length) {
throw new ArgumentOutOfRangeException(...);
}
}
private int[ ] bits;
private int length;
}والجزء الذي أريد فهمة هو هذه السطور من الكود فقط
this.bits = new int[((length - 1) >> 5) + 1]; return (bits[index >> 5] & (1 << index)) != 0; bits[index >> 5] |= (1 << index); bits[index >> 5] &= ~(1 << index);
وهذا هو الشرح الخاص به
1. Store 32 bools in one int. BitArray uses substantially less memory than a corresponding bool array by storing the state for 32 bools in one int. (Remember that int is an alias for Int32.) 2. Implement an indexer: public bool this[int index] The BitArray class contains an indexer to allow a BitArray object to be used in an array-like manner. In fact, a BitArray can be used exactly like a bool [ ]. BitArray flags = new BitArray(32); flags[12] = false; 3. Extract the individual bits. To extract the individual bits, you must shift the bits. For example, the following expression appears frequently because shifting right by 5 bits is equivalent to dividing by 32, because 2*2*2*2*2 == 2^5 == 32. Therefore, the following shift expression locates the int that holds the bit at position index: index >> 5 4. Determine the value of the correct bit. After the correct int is found, the individual bit (out of all 32) still needs to be determined. You can do this by using the following expression: 1 << index To understand how this works, you need to know that when you shift an int left only the lowest 5 bits of the second argument are used. (Again, only 5 bits are used because the int being shifted has 32 bits.) In other words, the above shift-left expression is semantically the same as the following: 1 << (index % 32)




