How to turn off some bits while ignoring others using only bitwise operators

Ben Leggiero picture Ben Leggiero · Jan 23, 2012 · Viewed 17.2k times · Source

I've searched for this, but my results were unsatisfactory, probably because of how hard it is to word. I have one object, state, which is a byte that represents which parts of my object are to be rendered when observed, and a method, disableParts(byte partsToDisable), which will turn off all bits in state that are ON in partsToDisable. How do I achieve this functionality in bitwise operations? (that is, only using AND, OR, XOR, NOT, LSHIFT, ARSHIFT, LRSHIFT, PLUS, MINUS, MULTIPLY, and/or DIVIDE and basic program functions such as loops and branching statements)

For a bit of clarity, here is a visual representation of my desired functionality:

  0010 0101 (current state, 37 in this example)
? 1010 0010 (bits to disable, -94 in this example)
============
  0000 0101 (new state, 5 in this example)

and a dummy class (in Java because that's how I think, but the solution can be any language or pseudo-code):

class BitThoughts
{
  byte state;

  public void doIt()
  {
    state = 0b00100101;
    System.out.println("Initial state: " + state);

    disableParts(0b10100010);

    if (state == 0b00000101)
      System.out.println("Success! New state is " + state);
    else
      System.out.println("Failure! New state is " + state);
  }

  public void disableParts(byte partsToDisable)
  {
    //Do magic to state
  }
}

Answer


Just so no one derps as hard as I did... here's the answer:

   0010 0101 (current state, 37 in this example)
& ~1010 0010 (bits to disable, -94 in this example)
=============

becomes:

   0010 0101 (current state: 37)
&  0101 1101 (inverted bits to disable: 93)
=============
   0000 0101 (new state, 5 in this example)

and the solution in Java:

public void disableParts(byte partsToDisable)
{
  state &= ~partsToDisable;
}

Answer

Andrew Cooper picture Andrew Cooper · Jan 23, 2012

What you need to do is invert the bits (bit-wise NOT) in partsToDisable so you end up with a mask where the 1's are the bits to be left alone and the 0's are the bits to be turned off. Then AND this mask with the state value.

public void disableParts( byte partsToDisable)
{
    state = state & (~partsToDisable);
}