Today we’ll look at the third out of four bitwise operators – bitwise XOR.
Bitwise XOR is represented by the symbol ^ and is an exclusive OR operation.
Can I see an example?
130 ^ 10 = 136
What is this actually doing?
Bitwise XOR compares each bit setting and if either one is set, sets the corresponding output bit to 1. However, if both bits are set, then the corresponding output bit is set to zero.
So to clarify, both OR and XOR compare each bit setting and if either one is set, sets the corresponding output bit to 1. However, if both bits are set, OR sets the output to 1, while XOR sets the output to zero.
In short, XOR gives a result of 1 only if the two inputs are different.
So the example above has bit comparisons as follows:
10000010 // 130
00001010 // 10
________
10001000 // 136
What would I use bitwise XOR for?
Let’s take a look at how we might use XOR.
Toggling with with XOR
XOR is primarily used to toggle bits on and off. Let’s say we have a byte which represents 8 boolean values and we want to turn the first two off and on again. We can use the same mask to toggle the bits we are interested in if we use the XOR operator.
10000111 // 135
00000011 // 3
________
10000100 // 132
Applying the mask turns off the last two bits.
10000100 // 132
00000011 // 3
________
10000111 //135
Applying it again turns the bits back on.
All the other bits remain unchanged. XOR is just like applying a switch – very useful in low level programming.
Next week we’ll take a look at bitwise NOT. Have fun!