0

I have the following items

Apple= 00000001 (1)

Mango= 00000010 (2)

Banana= 00000100 (4)

Grapes= 00001000 (8)

Now I am storing the fruits a user can have like this by doing or'd

UserA- 00000001(Apple) or'd 00000010(Mango) = 00000011 (i.e 3)

Now I want to check whether that user contains Apple or Banana ? Till now I am thinking this : (UserA's-Values) & (Apple|Banana ) =(Apple|Banana )

i.e (00000011)&(00000001|00000100 ) =(00000001|00000100 )

but it is not working ? May I know what I am missing ?

Rocky Singh
  • 15,128
  • 29
  • 99
  • 146

2 Answers2

4

You're checking for Apple AND Banana. The expression should be (UserA's-Values) & (Apple|Banana) (!= 0)

KRASH
  • 316
  • 4
  • 5
0

Bits can be stored and manipulated in both Enum and Struct as well.

For Enum: http://msdn.microsoft.com/en-us/library/cc138362.aspx
For Struct: Bit fields in C#

Enums are nice as .ToString() will print a coma-separated list of the elements, but you still use standard AND/OR operators to manipulate and test against it.

Community
  • 1
  • 1
Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97