Here's an informal and (hopefully simple to understand) by-example derivation of "next larger integer with same popcount" implementation that saturates to known when none exists. From there builds "closest smaller integer", "at runtime selected direction" and shows the connection to recent post by @harold that walks to "closest". If I didn't screw up it should be UB free.
https://marc-b-reynolds.github.io/math/2023/11/09/PopNextPrev.html