I'm trying to find the largest 1 << n
that satisfies this inequality (all variables are positive integers):
a & ~((1 << n) - 1) >= b
Solving this iteratively is trivial (and yes, I know you can get better performance through divide-and-conquer and the like), but that's not my question.
I'm wondering if there is a way this could be solved directly, like through bit-twiddling of some sort?
Note 1: Assume you can do "round up/down to the closest power of 2" in one operation.
Note 2: If necessary, you can assume a two's complement representation (but I doubt this helps).
What technique can I use to solve this, if there is a direct way? If there isn't, can I tell somehow?
I've tried lots of things like XORing a
and b
, rounding the result up to the next power of 2, etc. but I didn't end up finding anything nice that always works.
We have 4 cases: