L
Lax
Why is the "x&(x-1)" trick for removing the least significant set bit
from an integer only valid on 2's complement systems?
from an integer only valid on 2's complement systems?
Lax said:Why is the "x&(x-1)" trick for removing the least significant set bit
from an integer only valid on 2's complement systems?
Lax said:Why is the "x&(x-1)" trick for removing the least significant set bit
from an integer only valid on 2's complement systems?
Why is the "x&(x-1)" trick for removing the least significant set bit
from an integer only valid on 2's complement systems?
Lax said:Thank you all (for suggesting and showing
counterexamples).
So is this a good implementation-independent way of doing it?
(signed)( x & ( (unsigned)x-1 ) )
Eric said:It is valid on all systems if `x' is non-negative.
That means, as a particularly useful special case, that
it is always valid if `x' is unsigned.
For negative values of `x', I suggest you take pencil
and paper and work through a few examples, using all three
of the representations C allows: two's complement, ones'
complement, and signed magnitude. To save some writing,
pretend your computer uses a narrow int of maybe six or
eight bits. Try a few different `x' values like -1, -2,
-10, and see what happens.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.