After reading through your question carefully, it is clear that this is not actually the Find First Set-operation as others have answered as Find First Set would give you the largest value $n$ for which $p = 2^n$ is a factor of your number, whereas what you where asking for was the corresponding $p$.
This is good as the final step from your question to FFS is the most complicated part.
Assuming that your numbers are in a normal two's-complement encoding, the result should be a number with the same trailing zeroes and lowest one bit (if present) as $x$ and the remaining bits set to zero.
Using a few bit-twiddling hacks we can find the result in just a few steps:
- Take the bitwise inverse of $x$ to get a number that has all bits set differently.
- Add one to the inverse to restore only the trailing zeroes and the lowest one.
- Take the bitwise and between this value and the original number to set all bits not affected by the previous step to zero.
As these are very simple instructions they should exist in pretty much any language you can think of, and they usually look the same.
For example this is how it looks in C, C++, Python, Java, and Javascript: p = x & (~x + 1)
If anyone has an example of a language where it looks different, please add a comment.
Edit:
A simplification that was previously overlooked is using that -x
in two's complement is defined as ~x + 1
giving the even shorter code of p = x & -x
.