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

Julia Lawall <[email protected]>
Newsgroups org.kernel.vger.kernel-janitors
Message-ID <[email protected]>

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.

julia

>
> The power of two check would 'normally' use the negation:
> 	'if (!(a & (a - 1)))'
>
> Just a heads up so anyone else reading this doesn't go blindly swapping
> out this pattern for 'is_power_of_2()'.
>
> You need to apply some thinking. No 'sed' work.
>
> Br,
> Linus
>
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.