^ - bitwise XOR (exclusive OR)
suggest change#include <iostream>
#include <string>
int main(int argc, char **argv) {
int a = 5; // 0101b (0x05)
int b = 9; // 1001b (0x09)
int c = a ^ b; // 1100b (0x0C)
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
}
a = 5, b = 9, c = 12
Why
A bit wise XOR
(exclusive or) operates on the bit level and uses the following Boolean truth table:
true OR true = false
true OR false = true
false OR false = false
Notice that with an XOR operation true OR true = false
where as with operations true AND/OR true = true
, hence the exclusive nature of the XOR operation.
Using this, when the binary value for a
(0101
) and the binary value for b
(1001
) are XOR
’ed together we get the binary value of 1100
:
int a = 0 1 0 1
int b = 1 0 0 1 ^
---------
int c = 1 1 0 0
The bit wise XOR does not change the value of the original values unless specifically assigned to using the bit wise assignment compound operator ^=
:
#include <iostream>
int main(int argc, char **argv) {
int a = 5; // 0101b (0x05)
a ^= 9; // a = 0101b ^ 1001b
std::cout << "a = " << a << std::endl;
}
a = 12
also in 2015+ compilers variables may be assigned as binary:
int cn = 0b0111;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents