5

I can see in this tutorial on bit manipulation, under the heading "Extracting every last bit", that -

Suppose we wish to find the lowest set bit of x (which is known to be non-zero). If we subtract 1 from x then this bit is cleared, but all the other one bits in x remain set.

I don't understand how this statement is true.

If we take x = 110, subtracting 1 would give 101.

Here, the lowest set bit is not cleared. Can anyone tell me how I'm approaching this problem in a wrong way?

1 Answers1

8

After subtracting 1, you need to & the two values. e.g.

int bitremoved = x & (x-1);

In your example you end up with binary 100.

user949300
  • 9,009