Title says it all. I understand that &x gives x's address, but I came across multiple examples of lines like (x & y) today and I haven't been able to find any explanation. It's a hard question to search for.
Asked
Active
Viewed 118 times
-3
-
1Protip: It's a lot easier to search for after finding the name in an [operator precedence page](https://en.cppreference.com/w/cpp/language/operator_precedence). Works pretty well for most languages. – chris Jun 15 '20 at 05:44
-
2`x & y` is the bitwise AND operation. (x and y have to be integral values.) FYI: [Bitwise logic operators](https://en.cppreference.com/w/c/language/operator_arithmetic#Bitwise_logic) – Scheff's Cat Jun 15 '20 at 05:44
1 Answers
0
This is the biwise and. It will perform a logical and
between all bits of the integers a and b.
It is usually used for masking, which means clearing (forcing bits to zero) of some parts of an integer.
Exemple: I have a color code stored in a variable rgb
with 8 bits encoding the red component, 8 bits encoding the green componant and 8 bits encoding the blue component. If I want to extract the blue component I will use a &
mask the following way:
int b = rgb & 0xF; // keep the last 4 bits, clear the upper bits of rgb

kriss
- 23,497
- 17
- 97
- 116