Frederic
Frederic

Reputation: 387

.NET Enum and BitFlags

I’m using [Enum] as part of a list for special template in my pages..

<Flags>
Enum SMARTTAGS As Long
 ITEM01 = 1 << 1
 ITEM02 = 1 << 2
 ITEM03 = 1 << 3
 ITEM04 = 1 << 4
 ITEM05 = 1 << 5
 …
 ITEM31 = 1 << 31
 ITEM32 = 1 << 32
 ITEM33 = 1 << 33
 ITEM34 = 1 << 34
End Enum

Those [Enum] are regrouped as follow for simplicity;

<Flags>
 Enum SMARTTAGSGROUP As Long
  GROUP1 = ITEM01 OR ITEM02 OR ITEM03 OR … OR ITEM15
  GROUP2 = ITEM31 OR ITEM32 OR ITEM33 OR ITEM34
End Enum

Now – When I select GROUP2 : rather then giving me ITEM31/32/33/34 (4 items), I get ITEM1/2/31/32/33 (5 items )…. Indeed, in term of bitflags, it gave me 1,2, 1073741824 & -2147483648.

So I have 2 questions :

Many thanks for your answer.

Fred

Upvotes: 0

Views: 45

Answers (1)

Joey
Joey

Reputation: 354546

ITEM32, ITEM33, and ITEM34 have the values 0, 1, and 2 because the shift operator masks the right operand to five bits for integers:

To prevent a shift by more bits than the result can hold, Visual Basic masks the value of amount with a size mask that corresponds to the data type of pattern. The binary AND of these values is used for the shift amount. The size masks are as follows:

...
Integer, UInteger: 31 (decimal), &H0000001F (hexadecimal)
Long, ULong: 63 (decimal), &H0000003F (hexadecimal)
...

<< Operator (Visual Basic)

So you need to change the declaration as follows:

ITEM31 = 1 << 31
ITEM32 = 1L << 32
ITEM33 = 1L << 33
ITEM34 = 1L << 34

This will cause the shift operator to be the Long shift operator, thus allowing the shift amounts you specified.

Upvotes: 2

Related Questions