Ky -
Ky -

Reputation: 32103

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

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
  }
}

Upvotes: 22

Views: 22832

Answers (2)

Andrew Cooper
Andrew Cooper

Reputation: 32576

You need to 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);
}

Upvotes: 37

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

If you just invert the bits of the parts, you can just AND it with the state

 void disableParts(byte parts) {
     byte invertOfParts = 0b11111111 - parts;
     state &= invertOfParts
 }

Upvotes: 1

Related Questions