^ - bitwise XOR (exclusive OR)

suggest change
// :glot
#include <iostream>

int main() {
    const int a = 5;     // 0101b  (0x05)
    const int b = 9;     // 1001b  (0x09)
    const int c = a ^ b; // 1100b  (0x0C)
    
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << '\n';
}
a = 5, b = 9, c = 12

Why

A bitwise XOR (exclusive or) operates on the bit level and uses the following Boolean truth table:

true XOR true = false
true XOR false = true
false XOR false = false

Notice that true XOR true is false, whereas true AND true and true OR true are true. That is the exclusive part of XOR.

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 bitwise XOR does not change the value of the original values unless specifically assigned to using the bitwise assignment compound operator ^=:

// :glot
#include <iostream>

int main() {
    int a = 5;  // 0101b  (0x05)
    a ^= 9;    // a = 0101b ^ 1001b

    std::cout << "a = " << a << '\n';
}
a = 12

Since C++14, an integer literal may be written in binary:

int cn = 0b0111;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents