--- Quote Start ---
I know it's wrong
--- Quote End ---
As I said, I got a correct result with your above function, so I know it
can be right. To make the problem observed in your usage of the function understandable, you should give a code example, that allows to reproduce it. At present, I don't expect, that the problem is related to the function itself.
For the function coding, i would prefer a form that represents the intended operation more clearly: Search the leftmost bit != 0, set all bits right of it. But the result should be identical in any case.