Re: more potential janitor work: simplifying test for power of 2

Linus Probert
2026-04-02T11:57:30Z

On Thu Apr 2, 2026 at 12:07 PM CEST, Julia Lawall wrote:
>
>
> On Thu, 2 Apr 2026, Linus Probert wrote:
>
>> I took a closer look at this. Many of the occurences here are actually
>> used to check if a binary flag has more then one bit set. This is quite
>> a common pattern.
>>
>> Eg. 'if (a & (a - 1))' would pass if a = 0b100, not if a = 0b110. Since:
>> 0b100 - 0b001 = 0b011 -> (0b100 & 0b011) => false
>> 0b110 - 0b001 = 0b101 -> (0b100 & 0b101) => true
>
> If it's common, maybe there should be a function for it that properly
> reflects the intended behavior.
>

Not my decision but I would guess that the general consensus is that we
don't want to obscure bit manipulation in helper functions.

These patterns are often considered base knowledge and since it doesn't take
up any space a "helper" function only obscures what's happening. In
particular from a review perspective.

So unless there exists a function for this pattern already I don't think
it's something that merits replacing.

That's my 2c on that subject.

That said, there are certainly places where swapping in the
is_power_of_2() function is applicable. It uses a fancy bit trick which
wasn't as obvious to me. Generally the right side of the expression
below is the one I would use and no helper function existed.

(n - 1 < (n ^ (n - 1))) == (n && !(n & (n - 1)))

So if you are looking into doing some janitor work in this area you
should keep in mind that, without that zero guard 'n &&' swapping the
function might be altering the logic.

So, a heads up is all.

Br,
Linus