Home > Software engineering >  Can't we use the XOR operation (by masking) to change the i'th bit, instead of doing (~) o
Can't we use the XOR operation (by masking) to change the i'th bit, instead of doing (~) o

Time:09-24

Here is the simple code I have written in Java to change the ith bit by using the XOR operation.

public class xor {

    public static void main(String[] args) {
        
        int n = 46;
        int i = 2;
        
        int mask = 1<<i;
        System.out.println(n^mask); 
    }
}

CodePudding user response:

Sure, you can do that.

I interpret your question as:

"Doesn't it strike everybody as a lot simpler to use n^mask to turn a bit off, vs the more commonly observed pattern of n&(~mask)?"

The reason the vast majority of examples will use n&(~mask) is that this will turn the bit off if it is on, and it does nothing if it was already off. Your XOR strategy indeed turns the bit off if it was on, but if the bit was already off, your strategy turns it back on. It's usually not a good idea to write code that is 'fragile' - fragile code is code that is more likely to fail in the future after updates are made to other parts of the code (i.e. the code is fine and passes all tests today, but it's like a well built house of cards. It'll stand and survive some wind, but if someone pulls a card out on the other side, the whole thing comes down. That's fragile code).

(n&(~mask)) is way less fragile. Yes, readability of code is also important, but I'd say that in the vast majority of cases, 'less fragile code' is more important than 'more readable code', if a tradeoff must be made.

CodePudding user response:

These are different operations:

  • xor will flip masked
  • and will clear if not set in the mask
  • or will set if set in the mask
  • binary not will flip all (same as xor with all ones mask)

so,

        System.out.println(n^mask); // will flip always
        System.out.println(n&~mask); // will clear not masked
        System.out.println(n|mask); // will set masked
  • Related