tags:

views:

49

answers:

2

I have a series of behaviors I want to enable/disable based on bit values. For example, the status of Behavior "A" is 0 or 1, Behavior "B" is 0 or 2, Behavior "C" is 0 or 4, etc. If the value of the variable containing the status is "5", I know Behavior "A" and "C" are enabled. "B" is not. My program should then toggle on A & C.

I'm not sure what this is called so hopefully someone here can give me a name and shove me in the right direction. How do I programmatically create the list of enabled functions based on the status variable? There may be 20-30 behaviors i want to control in this manner. Too many to manage manually.

+6  A: 

You can use a BitVector32 or BitArray. They abstract away bit manipulation from you.

If you want to manipulate individual bits in an int variable directly, you can use bitwise operators:

Check whether i-th bit is set or not:

bool isSet = (variable & (1 << i)) != 0;

Set i-th bit:

variable |= (1 << i);

Reset i-th bit:

variable &= ~(1 << i);

Toggle i-th bit:

variable ^= (1 << i);
Mehrdad Afshari
+1...very informative, use this with a Strategy Pattern
Stan R.
A: 

Here is a simple example:

class DispatchTable
{
 readonly Action[] _actions;

 public DispatchTable(params Action[] actions)
 {
  _actions = actions;
 }

 public void Execute(ulong actionsMask)
 {
  for (int bitIx = 0; bitIx < _actions.Length && actionsMask != 0; bitIx++, actionsMask >>= 1)
  {
   if ((actionsMask & 0x01) != 0)
    _actions[bitIx]();
  }   
 }

 static void Main(string[] args)
 {
  DispatchTable t = new DispatchTable(
   delegate() { Console.WriteLine(1); },
   delegate() { Console.WriteLine(2); },
   delegate() { Console.WriteLine(3); }
  );

  t.Execute(0x04);
  t.Execute(0x02);
  t.Execute(0x01);
  t.Execute(0x0F);
 }
}
csharptest.net