I found an interesting property about 1's complement when reading an interview preparation book.
The property says given a number X, we can generate a mask that shows the first set bit (from right to left) using the 1's complement as follows:
X & ~(X - 1)
where ~
stands for 1's complement.
For example, if X = 0b0011
then
0b0011 & 0b1101 = 0b0001
I understood that the author is doing the X-1
to flip the first non-zero bit from the right. But I'm curious as to how did he come up with the idea that taking a 1's complement of X-1
and &
ing it with X
would result into a bit-mask that shows the first non-zero bit in X.
Its my first time posting at StackOverflow, so my apologies if this question doesn't belong here.