This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Rebecca Tonks
almost 10 years

# What is actually happening with the XOR mask?

I got exactly the right code for this, but I don’t really understand what’s happening; why does the mask have to be all 1s? What does the mask actually do? What is the point of using this type of mask? Why is this one used to flip rather than the NOT mask?

Your mask is your test case of which you will compare the number against. XOR means one or the other is true but not both. Let’s take a basic example with the intention of flipping the bits. I am going to leave out the “0b” part and just use 0’s and 1’s.

From RIGHT to LEFT using XOR:

1 and 0 produce a 1 because only 1 of them is a 1. 1 and 1 produce a 0 because both are 1 1 and 1 produce a 0 because both are 1

Result: 001 –> This is exactly the opposite as what we started with which was 110.

Why make the mask all 1’s? Let’s try this again but we’ll make the mask all 0’s.

From RIGHT to LEFT using XOR:

0 and 0 produce a 0 because both are 0 0 and 1 produce a 1 because only 1 of them is a 1 0 and 1 produce a 1 because only 1 of them is a 1

Result: 110 –> We started with 110 so the bits did not change.

You can try this on paper with other mask combinations but only using XOR with a mask that has the bits turned on will result in the flipping of bits.

You can use the “~” operator but XOR lets you manage individual bits which has many more applications.

points
Submitted by C6Silver
almost 10 years

Rebecca Tonks almost 10 years

Brilliant, thank you! I was far too tired yesterday to get what I was looking at, but I understand now.

Loren Schwartz over 8 years

This is a good explanation. Can you provide some practical examples of how this would be used? Thanks

Jeremy Hutson over 8 years

1 vote

First,, you have the desired number `number = 0b01110101`. Using a mask, you can flip bits using XOR. If, for example, you wanted to change the 3rd and 6th bit of the number, then `mask = 0b00100100` `0b01110101 ^ 0b00100100 = 0b01010001` By doing XOR on the number and the mask, you get the answer

``````0 ^ 0 = 0
1 ^ 0 = 1
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 0 = 0
1 ^ 0 = 1
``````

Definition of XOR: If there is `0 ^ 0`, then the result is `0`, just like OR. if there is `0 ^ 1` or `1 ^ 0`, then the result is `1`, just like OR. However, if there is `1 ^ 1`, the result is `0`. You can use not, but you can’t modify individual bits.

points
Submitted by Thomas Le
almost 10 years