Swammerdami
Squadron Leader
Finally got it.A simple one-liner suffices. No loop is needed.
x-1 sets the last bit to 0, and all preceding bits before it to 1. XOR with original x to clear the irrelevant bits to zero. AND with original leaves only the desired bit active. It seems to work also for 0 and negative numbers, which is neat.Code:int lastbit(int y) { return ((x-1)^x)&x; }
Beautiful! Variations are possible, e.g. . . . return x&(~(x-1)); . . . The codes work whether the machine uses 2's-complement arithmetic or 1's-complement.
A programmer showed me this trick 52 years ago and I thought it was wonderful. After all these decades I'm surprised it's not better known, but I guess a large majority of programmers aren't into "bit twiddling" at all.
Big kudos to Jayjay for discovering the trick himself. We'll never know if I could have figured it out myself: the programmer 52 years ago only gave me a few seconds to think of an answer before revealing it himself.
(BTW, the trick is not useless! Sometimes you want to loop one-by-one over the 1-bits in a word: you may as well do it quickly.)