Bit wise and with negative number

int b = 12;
int a = b & (-b);

how the code b & (-b) working and what value is it giving…???


To get the greatest power of two that is a divisor of b:
return b & -b;

Visit the link to know more:

Result is 4 in this case.



So we need to find the greatest power of two that divides a given number. So the problem is basically reduces to finding the rightmost set bit of a number.

This is done as follows:

We know that 2’s complement of a number inverts every bit after the first set bit.
And applying AND operator on a number and it’s 2’s complement will have only the rightmost set bit due to the above property.

Thus b & (-b) works. :slight_smile:


Here the & operator is applied to the binary representation of 12 and -12. The binary representation of 12 is 1100 and that of -12 is 0100 (it is obtained by negating 1100 and adding 1 to it ie 0011+1 =0100, also known as 2’s complement).… 1100& 0100…… 0100 = 4Hence the value is 4. Theoretically & operation between two numbers x and -x gives the highest power of 2 which divides x.