In C, what does the & operator do when used like this: (x & y)?

233 Views Asked by At

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.

1

There are 1 best solutions below

0
kriss On

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 rgbwith 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