& - bitwise AND

suggest change
#include <iostream>

int main(int argc, char **argv) {
    int a = 6;     // 0110b  (0x06)
    int b = 10;    // 1010b  (0x0A)
    int c = a & b; // 0010b  (0x02)
    
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
}
a = 6, b = 10, c = 2

Why

A bit wise AND operates on the bit level and uses the following Boolean truth table:

TRUE  AND TRUE  = TRUE
TRUE  AND FALSE = FALSE
FALSE AND FALSE = FALSE

When the binary value for a (0110) and the binary value for b (1010) are AND’ed together we get the binary value of 0010:

int a = 0 1 1 0
int b = 1 0 1 0 &
        ---------
int c = 0 0 1 0

The bit wise AND 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 &= 10;    // a = 0101b & 1010b == 0

    std::cout << "a = " << a << std::endl;
}
a = 0

Feedback about page:

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



Table Of Contents