& - bitwise AND
suggest change// :glot
#include <iostream>
int main() {
const int a = 6; // 0110b (0x06)
const int b = 10; // 1010b (0x0A)
const int c = a & b; // 0010b (0x02)
std::cout << "a = " << a << ", b = " << b << ", c = " << c << '\n';
}
a = 6, b = 10, c = 2
Why
A bitwise 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 bitwise AND 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 &= 10; // a = 0101b & 1010b == 0
std::cout << "a = " << a << '\n';
}
a = 0
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents