Re: [PATCH] Introduce a boolean "single_bit_set" function.

David Daney
2009-04-23T19:57:33Z

Robert P. J. Day wrote:
> A boolean single_bit_set() routine would simplify the numerous
> constructs of the form (((n & (n - 1)) == 0)) when testing for
> single-bitness.
>
> Signed-off-by: Robert P. J. Day <rpjday@crashcourse.ca>
>
> ---
>
> This is similar to the current is_power_of_2() routine defined in
> include/linux/log2.h, which is mathematically identical but,
> semantically, should be defined independently just so the code is more
> readable.
>
> I'm open to an alternative function name.
>
> diff --git a/include/linux/bitops.h b/include/linux/bitops.h
> index 6182913..1c0c840 100644
> --- a/include/linux/bitops.h
> +++ b/include/linux/bitops.h
> @@ -45,6 +45,13 @@ static inline unsigned long hweight_long(unsigned long w)
> return sizeof(w) == 4 ? hweight32(w) : hweight64(w);
> }
>
> +static inline __attribute__((const))
> +bool single_bit_set(unsigned long n)
> +{
> + return (n != 0 && ((n & (n - 1)) == 0));
> +}
> +
> +

It would be nice to be able to override this per architecture.

For example a more efficient implementation on CPUs that have a
population count instruction (__builtin_popcountl()) might be:

static inline __attribute__((const))
bool singe_bit_set(unsigned long n)
{
return __builtin_popcountl(n) == 1;
}

Also, are we still putting 'inline' everywhere?

David Daney