I am working on a project and I need to calculate the least significant bit (LSB) and most significant bit (MSB) of integers.
Suppose $x$ is an $n$-bit unsigned integer ($n=16, 32$ or $64$). We know that $y=x \ \& \ ($~$x+1)$ clears all the bits of $x$ except for the LSB. This is lightning fast, just three operations. Is there something similar for the MSB? What is the fastest way to compute it?
I just came across this hack from an old book about chess programming:
$$ y=XOR(x,x-1)=00...001111...11, $$
where the leftmost $1$ in $y$ is the leftmost $1$ of $x$, ie the MSB of $x$. Then we can add $1$ and shift right by $1$. I am not an expert but I think it's faster than what we 've seen here.