I am debugging some code right now (VS 2019, .NET Framework 4.7.2), stopped at a breakpoint, using the Immediate Window to evaluate variables. I have a BitVector32
which I am not understanding its state. Here is the content of the IW:
stillInHand.ToString()
"BitVector32{00000000000000000000000000001100}"
stillInHand
{BitVector32{00000000000000000000000000001100}}
Data: 12
stillInHand[0]
true
stillInHand[1]
false
stillInHand[2]
false
stillInHand[3]
false
stillInHand[4]
true
stillInHand[5]
false
stillInHand[6]
false
stillInHand[7]
false
There have been no calls to any of the Create*
methods, and stillInHand
was created with the BitVector32(Int32)
ctor. Shouldn't indices 2 & 3 be true
and all the rest be false
?
Actually, this issue is related to the understanding of the index of BitVector32[ ]
.
First of all, stillInHand[1]
doesn’t mean to get the second bit of stillInHand(BitVector32). It represents this action: use 00 00 … 00 01
to perform &
(AND) operation with stillInHand(BitVector32).
For an example: stillInHand(BitVector32)
is 00 00 00 00 00 … 00 00 00 11 00
, and 1
is 00 00 00 00 00 … 00 00 00 00 01
. Then perform &
(AND) operation.
00 00 00 00 00 … 00 00 00 11 00 12 &(AND)
00 00 00 00 00 … 00 00 00 00 01 `1`
--------------------------------------------
00 00 00 00 00 … 00 00 00 00 00
And you can see that the last bit(focus on the index value 1
) changes from 1
to 0
, so the result will be false
, if you output or see the result of stillInHand[1]
.
So, for stillInHand[2]
, you can see
00 00 00 00 00 … 00 00 00 11 00 12 &(AND)
00 00 00 00 00 … 00 00 00 00 10 2
--------------------------------------------
00 00 00 00 00 … 00 00 00 00 00
The second to last bit(focus on the index value 2
) changes from 1
to 0
, so the result will be false
too.
And for stillInHand[8]
, you can see
00 00 00 00 00 … 00 00 00 11 00 12 &(AND)
00 00 00 00 00 … 00 00 00 10 00 8
--------------------------------------------
00 00 00 00 00 … 00 00 00 10 00
The fourth to last bit(focus on the index value 8
) doesn’t change and it remains as 1
, so the result will be true
.
Actually, if you analyze the source code from here: Reference Source, you can see these codes:
/// <devdoc>
/// <para>Gets or sets a value indicating whether all the specified bits are set.</para>
/// </devdoc>
public bool this[int bit] {
get {
return (data & bit) == (uint)bit;
//clear other bits (to 0) through the AND operation of the data and mask.
//If the result of the operation is equal to the mask, return true.
//Otherwisse, return false.
}
set {
if (value) {
data |= (uint)bit;
//data = data OR mask, set the specified bit to “1”
}
else {
data &= ~(uint)bit;
//data = data AND ~mask, set the specified bit to “0”
}
}
}
Of course, you can consider it
as mask
, and this will be easy to understand.