For an unsigned integer j
, the operation j&(-j)
clears all but the least significant 1 bit, where -j
is the negative of j
treating j
as a signed integer. https://en.wikipedia.org/wiki/Find_first_set
Is there a similar simple operation that clears all but the most significant 1 bit?
An obvious solution is using clz
(count leading zeros) operation which is present in nearly all contemporary processors. There is also a question Previous power of 2 with an answer that is said to work even faster than clz
on old AMD processors. See also What is fastest method to calculate a number having only bit set which is the most significant digit set in another number?
My question is whether there is something simpler than using clz
which may not be easily accessible in certain languages. Note that I need the most significant 1 bit itself, not its position (logarithm).