I stumbled upon this question trying to find out what CreateMask
does exactly. I did not feel the current answers answered the question for me. After some reading and experimenting, I would like to share my findings:
Basically what Maksymilian says is almast correct: "BitVector32.CreateMask is a substitution for the left shift operator (<<) which in most cases results in multiplication by 2".
Because << is a binary operator and CreateMask only takes one argument, I would like to add that BitVector32.CreateMask(x)
is equivalant to x << 1
.
Bordercases
However, BitVector32.CreateMask(x)
is not equivalant to x << 1
for two border cases:
BitVector32.CreateMask(int.MinValue)
:
An InvalidOperationException will be thrown. int.MinValue
corresponds to 10000000000000000000000000000000
. This seems bit odd. Especially considering every other value with a 1 as the leftmost bit (i.e. negative numbers) works fine. In contrast: int.MinValue << 1
would not throw an exception and just return 0.
When you call BitVector32.CreateMask(0)
(or BitVector32.CreateMask()
). This will return 1
(i.e. 00000000000000000000000000000000
becomes 00000000000000000000000000000001
),
whereas 0 << 1 would just return 0.
Multiplication by 2
CreateMask almost always is equivalent to multiplication by 2. Other than the above two special cases, it differs when the second bit from the left is different from the leftmost bit. An int is signed, so the leftmost bit indicates the sign. In that scenario the sign is flipped. E.g. CreateMask(-1)
(or 11111111111111111111111111111111
) results in -2 (or 11111111111111111111111111111110
), but CreateMask(int.MaxValue)
(or 01111111111111111111111111111111
) also results in -2.
Anyway, you probably shouldn't use it for this purpose. As I understand, when you use a BitVector32, you really should only consider it a sequence of 32 bits. The fact that they use ints in combination with the BitVector32 is probably just because it's convenient.
When is CreateMask useful?
I honestly don't know. It seems from the documentation and the name "previous" of the argument of the function that they intended it to be used in some kind of sequence: "Use CreateMask() to create the first mask in a series and CreateMask(int) for all subsequent masks.".
However, in the code example, they use it to create the masks for the first 5 bits, to subsequently do some operations on those bits. I cannot imagine they expect you to write 32 calls in a row to CreateMask to be able to do some stuff with the bits near the left.