Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the CreateMask function of BitVector32 do?

Tags:

c#

.net

bitvector

What does the CreateMask() function of BitVector32 do? I did not get what a Mask is.

Would like to understand the following lines of code. Does create mask just sets bit to true?

  // Creates and initializes a BitVector32 with all bit flags set to FALSE.
  BitVector32 myBV = new BitVector32( 0 );

  // Creates masks to isolate each of the first five bit flags.
  int myBit1 = BitVector32.CreateMask();
  int myBit2 = BitVector32.CreateMask( myBit1 );
  int myBit3 = BitVector32.CreateMask( myBit2 );
  int myBit4 = BitVector32.CreateMask( myBit3 );
  int myBit5 = BitVector32.CreateMask( myBit4 );

  // Sets the alternating bits to TRUE.
  Console.WriteLine( "Setting alternating bits to TRUE:" );
  Console.WriteLine( "   Initial:         {0}", myBV.ToString() );
  myBV[myBit1] = true;
  Console.WriteLine( "   myBit1 = TRUE:   {0}", myBV.ToString() );
  myBV[myBit3] = true;
  Console.WriteLine( "   myBit3 = TRUE:   {0}", myBV.ToString() );
  myBV[myBit5] = true;
  Console.WriteLine( "   myBit5 = TRUE:   {0}", myBV.ToString() );

What is the practical application of this?

like image 855
Sunder Avatar asked Nov 26 '25 01:11

Sunder


1 Answers

It returns a mask which you can use for easier retrieving of interesting bit.

You might want to check out Wikipedia for what a mask is.

In short: a mask is a pattern in form of array of 1s for the bits that you are interested in and 0s for the others.

If you have something like 01010 and you are interested in getting the last 3 bits, your mask would look like 00111. Then, when you perform a bitwise AND on 01010 and 00111 you will get the last three bits (00010), since AND only is 1 if both bits are set, and none of the bits beside the first three are set in the mask.

An example might be easier to understand:

BitVector32.CreateMask() => 1 (binary 1)
BitVector32.CreateMask(1) => 2 (binary 10)
BitVector32.CreateMask(2) => 4 (binary 100)
BitVector32.CreateMask(4) => 8 (binary 1000)

CreateMask(int) returns the given number multiplied by 2.

NOTE: The first bit is the least significant bit, i.e. the bit farthest to the right.

like image 146
Arnis Lapsa Avatar answered Nov 27 '25 15:11

Arnis Lapsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!