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

前端 未结 2 551
感动是毒
感动是毒 2021-02-04 02:55

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

2条回答
  •  伪装坚强ぢ
    2021-02-04 03:15

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

提交回复
热议问题